Просмотр исходного кода

Merge branch 'runhey:dev' into dev

LHY 10 месяцев назад
Родитель
Сommit
0782cd8b65
100 измененных файлов с 1877 добавлено и 960 удалено
  1. 65 0
      .github/workflows/github-mirror.yml
  2. 1 1
      .gitignore
  3. 2 2
      README.md
  4. 3 0
      assets/i18n/en-US.json
  5. 9 0
      assets/i18n/zh-CN.json
  6. 3 0
      deploy/docker/.dockerignore
  7. 37 0
      deploy/docker/Dockerfile
  8. 32 0
      deploy/docker/Dockerfile.cn
  9. 172 0
      deploy/docker/requirements.txt
  10. 62 0
      deploy/docker/requirements_generator.py
  11. 3 3
      dev_tools/assets_test.py
  12. 13 0
      docker-compose.yaml
  13. 33 0
      module/atom/image.py
  14. 19 0
      module/atom/image_grid.py
  15. 7 0
      module/atom/list.py
  16. 8 0
      module/base/timer.py
  17. 29 0
      module/config/config_model.py
  18. 4 3
      module/device/control.py
  19. 0 1
      module/device/device.py
  20. 18 0
      module/device/method/windows.py
  21. 4 0
      module/device/method/windows_impl.py
  22. 3 3
      module/device/platform2/platform_windows.py
  23. 4 2
      module/device/screenshot.py
  24. 2 2
      module/gui/qml/Component/ResizableRectangle.qml
  25. 15 0
      module/gui/qml/Component/SplitPanel.qml
  26. 24 3
      module/gui/qml/Content/TaskList.qml
  27. 47 20
      module/server/app.py
  28. 10 0
      module/server/home_router.py
  29. 18 2
      module/server/i18n.py
  30. 16 3
      module/server/main_manager.py
  31. 21 6
      module/server/script_process.py
  32. 23 3
      module/server/script_router.py
  33. 12 7
      module/server/script_websocket.py
  34. 1 6
      module/server/updater.py
  35. 1 1
      requirements-in.txt
  36. 1 2
      requirements.txt
  37. 12 4
      script.py
  38. 2 2
      tasks/AbyssShadows/config.py
  39. BIN
      tasks/ActivityShikigami/0110/0110_c_confirm1.png
  40. BIN
      tasks/ActivityShikigami/0110/0110_n_battle.png
  41. BIN
      tasks/ActivityShikigami/0110/0110_n_confirm.png
  42. 0 26
      tasks/ActivityShikigami/0110/click.json
  43. 0 29
      tasks/ActivityShikigami/0110/image.json
  44. 180 0
      tasks/ActivityShikigami/README.md
  45. BIN
      tasks/ActivityShikigami/as/as_act_map_switch.png
  46. BIN
      tasks/ActivityShikigami/as/as_antivity_win.png
  47. BIN
      tasks/ActivityShikigami/as/as_battle.png
  48. BIN
      tasks/ActivityShikigami/as/as_battle_1.png
  49. BIN
      tasks/ActivityShikigami/as/as_battle_main_to_records.png
  50. BIN
      tasks/ActivityShikigami/as/as_battle_org.png
  51. BIN
      tasks/ActivityShikigami/as/as_boss.png
  52. BIN
      tasks/ActivityShikigami/as/as_buff_box_1_empty.png
  53. BIN
      tasks/ActivityShikigami/as/as_buff_box_2_empty.png
  54. BIN
      tasks/ActivityShikigami/as/as_buff_change_button.png
  55. BIN
      tasks/ActivityShikigami/as/as_buff_down.png
  56. BIN
      tasks/ActivityShikigami/as/as_buff_switch.png
  57. BIN
      tasks/ActivityShikigami/as/as_buff_up.png
  58. BIN
      tasks/ActivityShikigami/as/as_check_act_list_climb_act.png
  59. BIN
      tasks/ActivityShikigami/as/as_check_battle_2.png
  60. BIN
      tasks/ActivityShikigami/as/as_check_battle_main.png
  61. BIN
      tasks/ActivityShikigami/as/as_check_buff.png
  62. BIN
      tasks/ActivityShikigami/as/as_drum.png
  63. BIN
      tasks/ActivityShikigami/as/as_entry_activity.png
  64. BIN
      tasks/ActivityShikigami/as/as_lock.png
  65. BIN
      tasks/ActivityShikigami/as/as_new.png
  66. BIN
      tasks/ActivityShikigami/as/as_pass_act_locat.png
  67. BIN
      tasks/ActivityShikigami/as/as_red_exit_2.png
  68. BIN
      tasks/ActivityShikigami/as/as_shi.png
  69. BIN
      tasks/ActivityShikigami/as/as_to_battle_boss.png
  70. BIN
      tasks/ActivityShikigami/as/as_to_battle_main.png
  71. 7 49
      tasks/ActivityShikigami/as/click.json
  72. 3 201
      tasks/ActivityShikigami/as/image.json
  73. 83 0
      tasks/ActivityShikigami/as/pages.json
  74. 62 88
      tasks/ActivityShikigami/assets.py
  75. 72 29
      tasks/ActivityShikigami/config.py
  76. BIN
      tasks/ActivityShikigami/fire/fire_pass12.png
  77. BIN
      tasks/ActivityShikigami/fire/fire_pass_1.png
  78. BIN
      tasks/ActivityShikigami/fire/fire_pass_13.png
  79. BIN
      tasks/ActivityShikigami/fire/fire_pass_2.png
  80. BIN
      tasks/ActivityShikigami/fire/fire_pass_3.png
  81. BIN
      tasks/ActivityShikigami/fire/fire_pass_4.png
  82. BIN
      tasks/ActivityShikigami/fire/fire_pass_5.png
  83. BIN
      tasks/ActivityShikigami/fire/fire_pass_6.png
  84. BIN
      tasks/ActivityShikigami/fire/fire_pass_7.png
  85. BIN
      tasks/ActivityShikigami/fire/fire_pass_9.png
  86. 119 0
      tasks/ActivityShikigami/fire/image.json
  87. 30 20
      tasks/ActivityShikigami/fire/ocr.json
  88. 68 0
      tasks/ActivityShikigami/page.py
  89. 290 300
      tasks/ActivityShikigami/script_task.py
  90. 62 0
      tasks/ActivityShikigami/script_test.py
  91. 78 114
      tasks/AreaBoss/script_task.py
  92. 5 8
      tasks/BondlingFairyland/config_battle.py
  93. 4 2
      tasks/BondlingFairyland/script_task.py
  94. 49 15
      tasks/Component/BaseActivity/config_activity.py
  95. 2 0
      tasks/Component/Buy/assets.py
  96. 5 1
      tasks/Component/Buy/buy.py
  97. BIN
      tasks/Component/Buy/buy/buy_buy_success.png
  98. 9 0
      tasks/Component/Buy/buy/image.json
  99. 2 0
      tasks/Component/GeneralBattle/assets.py
  100. 11 2
      tasks/Component/GeneralBattle/gb/ocr.json

+ 65 - 0
.github/workflows/github-mirror.yml

@@ -0,0 +1,65 @@
+on:
+  schedule:
+    - cron: "0 4 * * *" # 北京时间中午12点 (UTC+8) = UTC 04:00
+    - cron: "0 10 * * *" # 下午六点
+    - cron: "0 17 * * *" # 凌晨一点
+  push:
+    branches:
+      - master
+name: GitHub-Mirrors
+
+jobs:
+  run:
+    name: Run
+    runs-on: ubuntu-latest
+    steps:
+      - name: Get repo and time
+        id: info
+        uses: actions/github-script@v3.1
+        with:
+          result-encoding: string
+          script: |
+            core.setOutput('time', new Date(Date.now()).toISOString().replace(/[^0-9]/g, ""));
+            core.setOutput('key', `${context.repo.owner}-${context.repo.repo}`);
+            return context.repo.repo;
+
+      - name: Cache src repos
+        uses: actions/cache@v4
+        id: cache
+        with:
+          path: ${{ github.workspace }}/hub-mirror-cache
+          key: ${{ runner.os }}-${{ steps.info.outputs.key }}-cache-${{ steps.info.outputs.time }}
+          restore-keys: ${{ runner.os }}-${{ steps.info.outputs.key }}-cache-
+
+      - name: Mirror the GitHub repos to Gitee with cache
+        uses: Yikun/hub-mirror-action@master
+        with:
+          src: github/runhey
+          dst: gitee/runheng
+          dst_key: ${{ secrets.GITEE_PRIVATE_KEY }} # 复用公钥
+          dst_token: ${{ secrets.GITEE_TOKEN }}
+          clone_style: ssh
+          static_list: "${{ steps.info.outputs.result }}"
+          cache_path: /github/workspace/hub-mirror-cache
+          account_type: user
+          force_update: true
+          white_list: "${{ steps.info.outputs.result }}"
+
+      - name: Mirror the GitHub repos to GitCode with cache
+        uses: Yikun/hub-mirror-action@master
+        with:
+          src: github/runhey
+          dst: gitcode/OnmyojiAutoScript
+          dst_key: ${{ secrets.GITEE_PRIVATE_KEY }} # 复用公钥
+          dst_token: ${{ secrets.GITCODE_TOKEN }}
+          clone_style: ssh
+          static_list: "${{ steps.info.outputs.result }}"
+          cache_path: /github/workspace/hub-mirror-cache
+          src_account_type: user
+          dst_account_type: org
+          force_update: true
+          white_list: "${{ steps.info.outputs.result }}"
+
+      - name: Print cache path
+        run: |
+          ls -la ${{ github.workspace }}/hub-mirror-cache

+ 1 - 1
.gitignore

@@ -35,7 +35,7 @@ module/config/i18n/*.json
 !dev_tools/ViewWizard2/ViewWizard2.exe
 !dev_tools/ViewWizard2/ViewWizard2.exe
 !dev_tools/ViewWizard3/ViewWizard.exe
 !dev_tools/ViewWizard3/ViewWizard.exe
 dev_tools/assets_test.py
 dev_tools/assets_test.py
-hya
+#hya
 deploy/launcher/oas-backend.bat
 deploy/launcher/oas-backend.bat
 deploy/launcher/oas-server.bat
 deploy/launcher/oas-server.bat
 oas-backend.bat
 oas-backend.bat

+ 2 - 2
README.md

@@ -69,7 +69,7 @@ OAS 在其基础上进行了如下优化:
 - [Alas](https://github.com/LmeSzinc/AzurLaneAutoScript): 碧蓝航线的自动化脚本
 - [Alas](https://github.com/LmeSzinc/AzurLaneAutoScript): 碧蓝航线的自动化脚本
 - [SRC](https://github.com/LmeSzinc/StarRailCopilot): 星铁速溶茶,崩坏:星穹铁道脚本,基于下一代Alas框架。
 - [SRC](https://github.com/LmeSzinc/StarRailCopilot): 星铁速溶茶,崩坏:星穹铁道脚本,基于下一代Alas框架。
 - [OASX](https://github.com/runhey/OASX): 同 OAS 对接的全平台 GUI
 - [OASX](https://github.com/runhey/OASX): 同 OAS 对接的全平台 GUI
-- [NikkeAutoScript](https://github.com/takagisanmie/NIKKEAutoScript): 胜利女神:NIKKE 自动日常脚本
+- [NikkeAutoScript](https://github.com/megumiss/NIKKEAutoScript): 胜利女神:NIKKE 自动日常脚本
 - [AAS](https://github.com/TheFunny/ArisuAutoSweeper): 蔚蓝档案自动化脚本
 - [AAS](https://github.com/TheFunny/ArisuAutoSweeper): 蔚蓝档案自动化脚本
 - [MAA](https://github.com/MaaAssistantArknights/MaaAssistantArknights): 明日方舟小助手,全日常一键长草
 - [MAA](https://github.com/MaaAssistantArknights/MaaAssistantArknights): 明日方舟小助手,全日常一键长草
 - [FGO-py](https://github.com/hgjazhgj/FGO-py): 全自动免配置跨平台开箱即用的Fate/Grand Order助手
 - [FGO-py](https://github.com/hgjazhgj/FGO-py): 全自动免配置跨平台开箱即用的Fate/Grand Order助手
@@ -84,7 +84,7 @@ OAS 在其基础上进行了如下优化:
 相对于其他的游戏,阴阳师玩家总体而言对脚本这类工具具有极高的排斥性。树大招风,无论你是否喜欢 OAS ,我们都希望你不在互联网上进行宣传,这保护 OAS , 也保护开发者们。
 相对于其他的游戏,阴阳师玩家总体而言对脚本这类工具具有极高的排斥性。树大招风,无论你是否喜欢 OAS ,我们都希望你不在互联网上进行宣传,这保护 OAS , 也保护开发者们。
 
 
 为此保持较高的入群门槛: 
 为此保持较高的入群门槛: 
-#### QQ交流群: 465946275
+#### QQ交流群: 1群465946275 2群1076565458
 - 你的QQ等级必须大于32级(🌞🌞),注册时间超过一年,低等级账号成分复杂,还请见谅。
 - 你的QQ等级必须大于32级(🌞🌞),注册时间超过一年,低等级账号成分复杂,还请见谅。
 - 你必须拥有一个 Github 账户来点一个 **Star** (这并不影响你入群后取消Star),同样的要求注册时间过半年。
 - 你必须拥有一个 Github 账户来点一个 **Star** (这并不影响你入群后取消Star),同样的要求注册时间过半年。
 - 入群验证填入你的 Github `username`(不是`name`),无需在意问题是什么,由QQ机器人审核(机器永远的对的)。
 - 入群验证填入你的 Github `username`(不是`name`),无需在意问题是什么,由QQ机器人审核(机器永远的对的)。

+ 3 - 0
assets/i18n/en-US.json

@@ -0,0 +1,3 @@
+{
+
+}

+ 9 - 0
assets/i18n/zh-CN.json

@@ -0,0 +1,9 @@
+{
+  "boss_limit_time": "单局Boss限制时间",
+  "kirin_battle_config": "麒麟战斗配置",
+  "netherworld_battle_config": "阴界之门战斗配置",
+  "hya_onmyoji": "切换阴阳师",
+  "hya_onmyoji_help": ""
+}
+
+

+ 3 - 0
deploy/docker/.dockerignore

@@ -0,0 +1,3 @@
+
+requirements_generator.py
+

+ 37 - 0
deploy/docker/Dockerfile

@@ -0,0 +1,37 @@
+# docker build -t qwerty/oas:latest .
+# docker run -v ${PWD}:/app/OnmyojiAutoScript -p 22288:22288 --name oas -it --rm qwerty/oas
+
+
+FROM python:3.10-slim-bookworm
+
+WORKDIR /app/OnmyojiAutoScript
+
+COPY requirements.txt /tmp/requirements.txt
+
+# python:3.10-slim is based on debian:12, apt source from https://developer.aliyun.com/mirror/debian
+RUN echo "\
+deb https://mirrors.cloud.tencent.com/debian/ bookworm main non-free non-free-firmware contrib \n\
+deb-src https://mirrors.cloud.tencent.com/debian/ bookworm main non-free non-free-firmware contrib \n\
+deb https://mirrors.cloud.tencent.com/debian-security/ bookworm-security main \n\
+deb-src https://mirrors.cloud.tencent.com/debian-security/ bookworm-security main \n\
+deb https://mirrors.cloud.tencent.com/debian/ bookworm-updates main non-free non-free-firmware contrib \n\
+deb-src https://mirrors.cloud.tencent.com/debian/ bookworm-updates main non-free non-free-firmware contrib \n\
+deb https://mirrors.cloud.tencent.com/debian/ bookworm-backports main non-free non-free-firmware contrib \n\
+deb-src https://mirrors.cloud.tencent.com/debian/ bookworm-backports main non-free non-free-firmware contrib \
+    "\
+> /etc/apt/sources.list\
+ && apt update \
+ && apt install -y git adb libgomp1 openssh-client \
+ && git config --global --add safe.directory '*' \
+ && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
+ && echo 'Asia/Shanghai' > /etc/timezone \
+ && pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple \
+ && pip install -r /tmp/requirements.txt \
+ && pip uninstall -y opencv-python\
+ && pip uninstall -y opencv-python-headless\
+ && pip install opencv-python-headless==4.7.0.72\
+ && rm /tmp/requirements.txt \
+ && rm -r ~/.cache/pip
+
+CMD python server.py
+#CMD /bin/bash

+ 32 - 0
deploy/docker/Dockerfile.cn

@@ -0,0 +1,32 @@
+# docker build -t qwerty/oas:latest .
+# docker run -v ${PWD}:/app/OnmyojiAutoScript -p 22288:22288 --name oas -it --rm qwerty/oas
+
+
+FROM python:3.10-slim-bullseye
+
+WORKDIR /app/OnmyojiAutoScript
+
+COPY requirements.txt /tmp/requirements.txt
+
+# python:3.10-slim is based on debian:11, apt source from https://developer.aliyun.com/mirror/debian
+RUN echo "\
+deb https://mirrors.aliyun.com/debian/ bullseye main non-free contrib\n\
+deb-src https://mirrors.aliyun.com/debian/ bullseye main non-free contrib\n\
+deb https://mirrors.aliyun.com/debian-security/ bullseye-security main\n\
+deb-src https://mirrors.aliyun.com/debian-security/ bullseye-security main\n\
+deb https://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib\n\
+deb-src https://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib\n\
+# deb https://mirrors.aliyun.com/debian/ bullseye-backports main non-free contrib\n\
+# deb-src https://mirrors.aliyun.com/debian/ bullseye-backports main non-free contrib" \
+> /etc/apt/sources.list \
+ && apt update \
+ && apt install -y git adb libgomp1 openssh-client \
+ && git config --global --add safe.directory '*' \
+ && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
+ && echo 'Asia/Shanghai' > /etc/timezone \
+ && pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple \
+ && pip install -r /tmp/requirements.txt \
+ && rm /tmp/requirements.txt \
+ && rm -r ~/.cache/pip
+
+ CMD python --version

+ 172 - 0
deploy/docker/requirements.txt

@@ -0,0 +1,172 @@
+#
+
+# This file is autogenerated by pip-compile with Python 3.10
+
+# by the following command:
+
+#    pip-compile --annotation-style=line --output-file=requirements.txt requirements-in.txt
+adbutils==0.11.0          
+# via -r requirements-in.txt, uiautomator2
+annotated-types==0.7.0    
+# via pydantic
+anyio==3.7.1              
+# via fastapi, starlette
+anytree==2.8.0            
+# via -r requirements-in.txt
+apkutils2==1.0.0          
+# via adbutils
+cached-property==1.5.2    
+# via uiautomator2
+certifi==2023.11.17       
+# via requests
+cffi==1.16.0              
+# via cryptography, gevent
+charset-normalizer==3.3.2  
+# via requests
+cigam==0.0.3              
+# via apkutils2
+click==8.1.7              
+# via uvicorn
+cn2an==0.5.23             
+# via -r requirements-in.txt
+colorama==0.4.6           
+# via click, logzero, tqdm
+coloredlogs==15.0.1       
+# via onnxruntime
+cryptography==42.0.8      
+# via -r requirements-in.txt
+decorator==5.1.1          
+# via retry
+deprecated==1.2.14        
+# via uiautomator2
+deprecation==2.1.0        
+# via adbutils
+exceptiongroup==1.2.0     
+# via anyio
+fastapi==0.104.1          
+# via -r requirements-in.txt
+filelock==3.13.1          
+# via uiautomator2
+flatbuffers==23.5.26      
+# via onnxruntime
+future==0.18.3            
+# via zerorpc
+gevent==23.9.1            
+# via zerorpc
+greenlet==3.0.3           
+# via gevent
+h11==0.14.0               
+# via uvicorn
+humanfriendly==10.0       
+# via coloredlogs
+idna==3.6                 
+# via anyio, requests
+inflection==0.5.1         
+# via -r requirements-in.txt
+logzero==1.7.0            
+# via uiautomator2
+lxml==5.0.0               
+# via uiautomator2
+markdown-it-py==2.2.0     
+# via rich
+mdurl==0.1.2              
+# via markdown-it-py
+mpmath==1.3.0             
+# via sympy
+msgpack==1.0.7            
+# via zerorpc
+numpy==1.24.3             
+# via -r requirements-in.txt, onnxruntime, opencv-python, ppocr-onnx, shapely
+oashya==0.0.7             
+# via -r requirements-in.txt
+onepush==1.3.0            
+# via -r requirements-in.txt
+onnxruntime==1.16.3       
+# via ppocr-onnx
+opencv-python-headless==4.7.0.72
+packaging==20.9           
+# via deprecation, onnxruntime, uiautomator2
+paho-mqtt==1.6.1          
+# via -r requirements-in.txt
+pillow==10.2.0            
+# via ppocr-onnx, uiautomator2
+ppocr-onnx==0.0.3.9       
+# via -r requirements-in.txt
+proces==0.1.7             
+# via cn2an
+progress==1.6             
+# via uiautomator2
+protobuf==4.25.1          
+# via onnxruntime
+psutil==6.1.1             
+# via -r requirements-in.txt
+py==1.11.0                
+# via retry
+pyclipper==1.3.0.post5    
+# via ppocr-onnx
+pycparser==2.21           
+# via cffi
+pycryptodome==3.21.0      
+# via onepush
+pydantic==2.10.0          
+# via -r requirements-in.txt, fastapi
+pydantic-core==2.27.0     
+# via pydantic
+pyelftools==0.30          
+# via apkutils2
+pygments==2.17.2          
+# via rich
+pyparsing==3.1.1          
+# via packaging
+pyreadline3==3.4.1        
+# via humanfriendly
+pyyaml==6.0               
+# via -r requirements-in.txt
+pyzmq==25.1.2             
+# via zerorpc
+requests==2.31.0          
+# via adbutils, onepush, ppocr-onnx, uiautomator2
+retry==0.9.2              
+# via adbutils, uiautomator2
+rich==13.3.5              
+# via -r requirements-in.txt
+shapely==2.0.2            
+# via ppocr-onnx
+six==1.16.0               
+# via adbutils, anytree, uiautomator2
+sniffio==1.3.0            
+# via anyio
+starlette==0.27.0         
+# via fastapi
+sympy==1.12               
+# via onnxruntime
+tqdm==4.65.0              
+# via -r requirements-in.txt
+typing-extensions==4.12.2  
+# via fastapi, pydantic, pydantic-core, uvicorn
+uiautomator2==2.16.17     
+# via -r requirements-in.txt
+uiautomator2cache==0.3.0.1  
+# via -r requirements-in.txt
+urllib3==2.1.0            
+# via requests
+uvicorn==0.23.2           
+# via -r requirements-in.txt
+websockets==11.0.3        
+# via -r requirements-in.txt
+whichcraft==0.6.1         
+# via adbutils, uiautomator2
+wrapt==1.15.0             
+# via -r requirements-in.txt, deprecated
+xmltodict==0.13.0         
+# via apkutils2
+zerorpc==0.6.3            
+# via -r requirements-in.txt
+zope-event==5.0           
+# via gevent
+zope-interface==6.1       
+# via gevent
+
+# The following packages are considered to be unsafe in a requirements file:
+
+# setuptools

+ 62 - 0
deploy/docker/requirements_generator.py

@@ -0,0 +1,62 @@
+import os
+
+from deploy.logger import logger
+
+BASE_FOLDER = os.path.dirname(os.path.abspath(__file__))
+logger.info(BASE_FOLDER)
+
+
+def read_file(file):
+    out = {}
+    with open(file, 'r', encoding='utf-8') as f:
+        for line in f.readlines():
+            if not line.strip():
+                continue
+            res = [s.strip() for s in line.split('==')]
+            if len(res) > 1:
+                name, version = res
+            else:
+                name, version = res[0], None
+            out[name] = version
+
+    return out
+
+
+def write_file(file, data):
+    lines = []
+    for name, version in data.items():
+        if version:
+            lines.append(f'{name}=={version}')
+        else:
+            lines.append(str(name))
+
+    with open(file, 'w', encoding='utf-8', newline='') as f:
+        text = '\n'.join(lines)
+        text = text.replace('#', '\n#').strip()
+        f.write(text)
+
+
+def docker_requirements_generate(requirements_in='requirements.txt'):
+    requirements = read_file(requirements_in)
+
+    logger.info(f'Generate requirements for Docker image')
+    lock = {}
+    new = {}
+    logger.info(requirements)
+    for name, version in requirements.items():
+        # alas-webapp is for windows only
+        if name == 'alas-webapp' or name == 'pywin32':
+            continue
+        if name == 'opencv-python':
+            name = 'opencv-python-headless'
+            version = '4.7.0.72'
+        if name in lock:
+            version = lock[name] if not isinstance(lock[name], dict) else lock[name]['version']
+            name = name if not isinstance(lock[name], dict) else lock[name]['name']
+        new[name] = version
+
+    write_file(os.path.join(BASE_FOLDER, f'./requirements.txt'), data=new)
+
+
+if __name__ == '__main__':
+    docker_requirements_generate()

+ 3 - 3
dev_tools/assets_test.py

@@ -34,10 +34,10 @@ def detect_ocr(file: str, target: RuleOcr):
 
 
 
 
 # 图片文件路径 可以是相对路径
 # 图片文件路径 可以是相对路径
-IMAGE_FILE = r"C:\Users\Ryland\Desktop\QQ20251014-103056.png"
+IMAGE_FILE = r"C:\Users\Ryland\Desktop\ScreenShot_2025-11-20_210804_069.png"
 if __name__ == '__main__':
 if __name__ == '__main__':
-    from tasks.KekkaiActivation.script_task import ScriptTask
-    targe = ScriptTask.I_UI_CONFIRM_SAMLL
+    from tasks.MetaDemon.script_task import ScriptTask
+    targe = ScriptTask.I_BOSS_EMPTY_2
     print(detect_image(IMAGE_FILE, targe))
     print(detect_image(IMAGE_FILE, targe))
 
 
     # ocr demo
     # ocr demo

+ 13 - 0
docker-compose.yaml

@@ -0,0 +1,13 @@
+
+services:
+    OAS:
+        network_mode: host
+        volumes:
+            - '.:/app/OnmyojiAutoScript:rw'
+            - '/etc/localtime:/etc/localtime:ro'
+        container_name: 'oas-env'
+        image: 'oas-env'
+        build:
+            context: ./deploy/docker/
+            dockerfile: ./Dockerfile
+            # dockerfile: ./Dockerfile

+ 33 - 0
module/atom/image.py

@@ -195,6 +195,39 @@ class RuleImage:
             matches.append((score, x, y, mat.shape[1], mat.shape[0]))
             matches.append((score, x, y, mat.shape[1], mat.shape[0]))
         return matches
         return matches
 
 
+    def match_all_any(self, image: np.array, threshold: float = None, roi: list = None, nms_threshold: float = 0.3) -> list[tuple]:
+        """
+        区别于match,这个是返回所有的匹配结果,去除冗余匹配项(例如:多个框选区域重叠的情况)时使用。
+        :param roi:
+        :param image:
+        :param threshold:
+        :return:
+        """
+        if roi is not None:
+            self.roi_back = roi
+        if threshold is None:
+            threshold = self.threshold
+        if not self.is_template_match:
+            raise Exception(f"unknown method {self.method}")
+        source = self.corp(image)
+        mat = self.image
+        results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        locations = np.where(results >= threshold)
+        matches = []
+        for pt in zip(*locations[::-1]):  # (x, y) coordinates
+            score = results[pt[1], pt[0]]
+            # 得分, x, y, w, h
+            x = self.roi_back[0] + pt[0]
+            y = self.roi_back[1] + pt[1]
+            matches.append((score, x, y, mat.shape[1], mat.shape[0]))
+        if len(matches) > 0:
+            scores = np.array([m[0] for m in matches])
+            boxes = np.array([[m[1], m[2], m[3], m[4]] for m in matches])
+            # 使用OpenCV的NMSBoxes
+            indices = cv2.dnn.NMSBoxes(boxes.tolist(), scores.tolist(), score_threshold=threshold, nms_threshold=nms_threshold)
+            filtered_matches = [matches[i] for i in indices]
+            return filtered_matches
+        return matches
 
 
     def coord(self) -> tuple:
     def coord(self) -> tuple:
         """
         """

+ 19 - 0
module/atom/image_grid.py

@@ -24,4 +24,23 @@ class ImageGrid:
                 return image
                 return image
         return None
         return None
 
 
+    def find_everyone(self, img: np.array) -> list or None:
+        """
+        自下而上查找所有匹配项,返回带对应image对象的排序结果
+        :param img: 待匹配图像
+        :return: 排序后的列表,每个元素为(image对象, (x, y, w, h)),无匹配返回None
+        """
+        matched = []
+        # 收集匹配结果时保留来源image
+        for image in self.images:
+            matches = image.match_all_any(img, threshold=0.8, nms_threshold=0.3)
+            for (score, x, y, w, h) in matches:
+                matched.append( (image, score, (x, y, w, h)) )
+
+        # 按y坐标升序排列(屏幕坐标系从上到下)
+        sorted_results = sorted(
+            matched,
+            key=lambda item: item[2][1]  # item[1]是坐标元组,取y值
+        )
 
 
+        return sorted_results if sorted_results else None

+ 7 - 0
module/atom/list.py

@@ -43,6 +43,13 @@ class RuleList:
         self._target = None  # 目标
         self._target = None  # 目标
         self.targets = {}  # 目标列表 只是针对image
         self.targets = {}  # 目标列表 只是针对image
 
 
+    @property
+    def name(self):
+        return f'RuleList[{self.__hash__()}]'
+
+    def __hash__(self):
+        return hash((self.folder, self.is_vertical, self.is_image, self.is_ocr, tuple(self.roi_back), tuple(self.size), tuple(self.array)))
+
     def swipe_pos(self, number: int=2, after: bool=True) -> tuple:
     def swipe_pos(self, number: int=2, after: bool=True) -> tuple:
         """
         """
         返回滑动的起始位置和终点位置
         返回滑动的起始位置和终点位置

+ 8 - 0
module/base/timer.py

@@ -153,11 +153,19 @@ class Timer:
         diff = self._current + self.limit - time.time()
         diff = self._current + self.limit - time.time()
         if diff > 0:
         if diff > 0:
             time.sleep(diff)
             time.sleep(diff)
+        return self
 
 
     def show(self):
     def show(self):
         from module.logger import logger
         from module.logger import logger
         logger.info(str(self))
         logger.info(str(self))
 
 
+    def remain(self):
+        """
+        remain time
+        :return:
+        """
+        return self._current + self.limit - time.time()
+
     def __str__(self):
     def __str__(self):
         return f'Timer(limit={round(self.current(), 3)}/{self.limit}, count={self._reach_count}/{self.count})'
         return f'Timer(limit={round(self.current(), 3)}/{self.limit}, count={self._reach_count}/{self.count})'
 
 

+ 29 - 0
module/config/config_model.py

@@ -409,6 +409,35 @@ class ConfigModel(ConfigBase):
             logger.error(e)
             logger.error(e)
             return False
             return False
 
 
+    def copy_script_task(self, task_name: str, source_task: BaseModel) -> bool:
+        model_task_name = convert_to_underscore(task_name)
+        try:
+            setattr(self, model_task_name, source_task)
+            self.save()
+            logger.info(f'Copy task {model_task_name} success')
+            return True
+        except ValidationError as e:
+            logger.error(e)
+            return False
+
+    def copy_task_group(self, task_name: str, group_name: str, source_task: BaseModel) -> bool:
+        model_task_name = convert_to_underscore(task_name)
+        model_group_name = convert_to_underscore(group_name)
+        task_object = getattr(self, model_task_name, None)
+        if not task_object:
+            return False
+        source_group_obj = getattr(source_task, model_group_name, None)
+        if not source_group_obj:
+            return False
+        try:
+            setattr(task_object, model_group_name, source_group_obj)
+            self.save()
+            logger.info(f'Copy task group {model_task_name}.{model_group_name} success')
+            return True
+        except ValidationError as e:
+            logger.error(e)
+            return False
+
     def replace_next_run(self, d, dt: datetime):
     def replace_next_run(self, d, dt: datetime):
         for k, v in d.items():
         for k, v in d.items():
             if isinstance(v, dict):
             if isinstance(v, dict):

+ 4 - 3
module/device/control.py

@@ -4,10 +4,11 @@ from module.base.timer import Timer
 from module.base.utils import *
 from module.base.utils import *
 # from module.device.method.hermit import Hermit
 # from module.device.method.hermit import Hermit
 # from module.device.method.maatouch import MaaTouch
 # from module.device.method.maatouch import MaaTouch
+from module.device.env import IS_WINDOWS
 from module.device.method.minitouch import Minitouch
 from module.device.method.minitouch import Minitouch
 from module.device.method.adb import Adb
 from module.device.method.adb import Adb
 from module.device.method.scrcpy import Scrcpy
 from module.device.method.scrcpy import Scrcpy
-from module.device.method.window import Window
+from module.device.method.windows import Window
 from module.logger import logger
 from module.logger import logger
 
 
 
 
@@ -22,7 +23,7 @@ class Control(Minitouch, Adb, Scrcpy, Window):
             'ADB': self.click_adb,
             'ADB': self.click_adb,
             'uiautomator2': self.click_uiautomator2,
             'uiautomator2': self.click_uiautomator2,
             'minitouch': self.click_minitouch,
             'minitouch': self.click_minitouch,
-            'window_message': self.click_window_message
+            'window_message': self.click_window_message if IS_WINDOWS else None,
             # 'Hermit': self.click_hermit,
             # 'Hermit': self.click_hermit,
             # 'MaaTouch': self.click_maatouch,
             # 'MaaTouch': self.click_maatouch,
         }
         }
@@ -33,7 +34,7 @@ class Control(Minitouch, Adb, Scrcpy, Window):
             'ADB': self.long_click_adb,
             'ADB': self.long_click_adb,
             'uiautomator2': self.long_click_uiautomator2,
             'uiautomator2': self.long_click_uiautomator2,
             'minitouch': self.long_click_minitouch,
             'minitouch': self.long_click_minitouch,
-            'window_message': self.long_click_window_message,
+            'window_message': self.long_click_window_message if IS_WINDOWS else None,
             'scrcpy': self.long_click_scrcpy
             'scrcpy': self.long_click_scrcpy
             # 'Hermit': self.click_hermit,
             # 'Hermit': self.click_hermit,
             # 'MaaTouch': self.click_maatouch,
             # 'MaaTouch': self.click_maatouch,

+ 0 - 1
module/device/device.py

@@ -22,7 +22,6 @@ from module.exception import (GameNotRunningError,
 from module.logger import logger
 from module.logger import logger
 
 
 
 
-
 class Device(Platform, Screenshot, Control, AppControl):
 class Device(Platform, Screenshot, Control, AppControl):
     _screen_size_checked = False
     _screen_size_checked = False
     detect_record = set()
     detect_record = set()

+ 18 - 0
module/device/method/windows.py

@@ -0,0 +1,18 @@
+
+
+from module.device.env import IS_WINDOWS
+
+
+if IS_WINDOWS:
+    from module.device.method.windows_impl import Window
+
+else:
+    class Window:
+        pass
+
+
+
+
+
+
+

+ 4 - 0
module/device/method/window.py → module/device/method/windows_impl.py

@@ -21,6 +21,7 @@ from win32ui import CreateDCFromHandle, CreateBitmap
 from win32api import GetSystemMetrics, SendMessage, MAKELONG, PostMessage
 from win32api import GetSystemMetrics, SendMessage, MAKELONG, PostMessage
 from win32con import SRCCOPY
 from win32con import SRCCOPY
 
 
+
 from module.base.cBezier import BezierTrajectory
 from module.base.cBezier import BezierTrajectory
 from module.exception import RequestHumanTakeover, ScriptError
 from module.exception import RequestHumanTakeover, ScriptError
 from module.base.decorator import Config
 from module.base.decorator import Config
@@ -29,6 +30,8 @@ from module.logger import logger
 from module.device.handle import Handle, window_scale_rate, EmulatorFamily
 from module.device.handle import Handle, window_scale_rate, EmulatorFamily
 
 
 
 
+
+
 class Window(Handle):
 class Window(Handle):
 
 
     def __init__(self, *args, **kwargs):
     def __init__(self, *args, **kwargs):
@@ -357,6 +360,7 @@ class Window(Handle):
 
 
 
 
 
 
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     w = Window(config='oas1')
     w = Window(config='oas1')
     # img = w.screenshot_window_background()
     # img = w.screenshot_window_background()

+ 3 - 3
module/device/platform2/platform_windows.py

@@ -342,7 +342,7 @@ class PlatformWindows(PlatformBase, EmulatorManager):
                 else:
                 else:
                     new_window = 0
                     new_window = 0
             try:
             try:
-                logger.info('Try to connect emulator, please waiting......')
+                logger.info(f'Try to connect emulator, remain[{timeout.remain():.1f}s]')
                 # Check device connection
                 # Check device connection
                 devices = self.list_device().select(serial=serial)
                 devices = self.list_device().select(serial=serial)
                 # logger.info(devices)
                 # logger.info(devices)
@@ -417,7 +417,7 @@ class PlatformWindows(PlatformBase, EmulatorManager):
 
 
     def emulator_start(self):
     def emulator_start(self):
         logger.hr('Emulator start', level=1)
         logger.hr('Emulator start', level=1)
-        for _ in range(3):
+        for i in range(3):
             # Stop
             # Stop
             if not self._emulator_function_wrapper(self._emulator_stop):
             if not self._emulator_function_wrapper(self._emulator_stop):
                 return False
                 return False
@@ -426,7 +426,7 @@ class PlatformWindows(PlatformBase, EmulatorManager):
                 # Success
                 # Success
                 if self.emulator_start_watch():
                 if self.emulator_start_watch():
                     return True
                     return True
-                # Failed to connect or start, try again
+                logger.attr(2 - i, f'Failed to connect or start, try again')
                 continue
                 continue
             else:
             else:
                 # Failed to start, stop and start again
                 # Failed to start, stop and start again

+ 4 - 2
module/device/screenshot.py

@@ -11,8 +11,9 @@ from PIL import Image
 from module.base.decorator import cached_property
 from module.base.decorator import cached_property
 from module.base.timer import Timer
 from module.base.timer import Timer
 from module.base.utils import get_color, image_size, limit_in, save_image
 from module.base.utils import get_color, image_size, limit_in, save_image
+from module.device.env import IS_WINDOWS
 from module.device.method.adb import Adb
 from module.device.method.adb import Adb
-from module.device.method.window import Window
+from module.device.method.windows import Window
 from module.device.method.droidcast import DroidCast
 from module.device.method.droidcast import DroidCast
 from module.device.method.scrcpy import Scrcpy
 from module.device.method.scrcpy import Scrcpy
 from module.device.method.nemu_ipc import NemuIpc
 from module.device.method.nemu_ipc import NemuIpc
@@ -43,7 +44,7 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window, NemuIpc):
             'DroidCast': self.screenshot_droidcast,
             'DroidCast': self.screenshot_droidcast,
             'DroidCast_raw': self.screenshot_droidcast_raw,
             'DroidCast_raw': self.screenshot_droidcast_raw,
             'scrcpy': self.screenshot_scrcpy,
             'scrcpy': self.screenshot_scrcpy,
-            'window_background': self.screenshot_window_background,
+            'window_background': self.screenshot_window_background if IS_WINDOWS else None,
             'nemu_ipc': self.screenshot_nemu_ipc
             'nemu_ipc': self.screenshot_nemu_ipc
         }
         }
 
 
@@ -272,4 +273,5 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window, NemuIpc):
 if __name__ == "__main__":
 if __name__ == "__main__":
     s = Screenshot(config="oas1")
     s = Screenshot(config="oas1")
     s.screenshot()
     s.screenshot()
+
     s.image_show()
     s.image_show()

+ 2 - 2
module/gui/qml/Component/ResizableRectangle.qml

@@ -3,8 +3,8 @@ import QtQuick.Window 2.15
 
 
 Item {
 Item {
     id:rect
     id:rect
-    property int minimumWidth: 20
-    property int minimumHeight: 20
+    property int minimumWidth: 5
+    property int minimumHeight: 5
     property int mouseRegion: 5
     property int mouseRegion: 5
     property var resizeTarget: rect
     property var resizeTarget: rect
     anchors.fill: resizeTarget
     anchors.fill: resizeTarget

+ 15 - 0
module/gui/qml/Component/SplitPanel.qml

@@ -37,6 +37,9 @@ Item {
         anchors.bottomMargin: 12
         anchors.bottomMargin: 12
 
 
         onLoaded: {
         onLoaded: {
+            if (!contentDefalut.item)
+                return
+
             if(typeof contentDefalut.item.splitPanel === "undefined"){
             if(typeof contentDefalut.item.splitPanel === "undefined"){
                 return
                 return
             }
             }
@@ -113,6 +116,10 @@ Item {
 //    }
 //    }
     //设置右边显示的参数项,输入的序列的字符串
     //设置右边显示的参数项,输入的序列的字符串
     function setLoaderData(args, value){
     function setLoaderData(args, value){
+        if (!contentLoader.item) {
+            console.log("SplitPanel: contentLoader.item is null in setLoaderData")
+            return
+        }
         contentLoader.item.argsData = args
         contentLoader.item.argsData = args
         contentLoader.item.valueData = value
         contentLoader.item.valueData = value
         contentLoader.item.updataData()
         contentLoader.item.updataData()
@@ -120,12 +127,20 @@ Item {
 
 
     //设置上下文
     //设置上下文
     function setLoaderContext(configName, taskName){
     function setLoaderContext(configName, taskName){
+        if (!contentLoader.item) {
+            console.log("SplitPanel: contentLoader.item is null in setLoaderContext")
+            return
+        }
         contentLoader.item.configName = configName
         contentLoader.item.configName = configName
         contentLoader.item.taskName = taskName
         contentLoader.item.taskName = taskName
     }
     }
 
 
     //设置配置的名称
     //设置配置的名称
     function setDefalutConfig(name){
     function setDefalutConfig(name){
+        if (!contentDefalut.item) {
+            console.log("SplitPanel: contentDefalut.item is null in setDefalutConfig")
+            return
+        }
         contentDefalut.item.configName = name
         contentDefalut.item.configName = name
     }
     }
 
 

+ 24 - 3
module/gui/qml/Content/TaskList.qml

@@ -143,8 +143,29 @@ Item{
 
 
     Component.onCompleted:{
     Component.onCompleted:{
 
 
-        const data = JSON.parse(process_manager.gui_task_list(MainEvent.scriptName))
-        const menu = JSON.parse(process_manager.gui_menu())
+        var rawTaskList = process_manager.gui_task_list(MainEvent.scriptName)
+        var rawMenu     = process_manager.gui_menu()
+
+        console.log("TaskList rawTaskList =", rawTaskList)
+        console.log("TaskList rawMenu =", rawMenu)
+
+        var data = {}
+        var menu = {}
+
+        try {
+            data = JSON.parse(rawTaskList)
+        } catch (e) {
+            console.error("TaskList: JSON.parse task_list error:", e, "raw =", rawTaskList)
+            return   // 解析失败就不要往下走了
+        }
+
+        try {
+            menu = JSON.parse(rawMenu)
+        } catch (e) {
+            console.error("TaskList: JSON.parse menu error:", e, "raw =", rawMenu)
+            return
+        }
+
         for(const key in menu){
         for(const key in menu){
             if(key === "Overview" || key === 'TaskList' || key === 'Script' || key === 'Tools'){
             if(key === "Overview" || key === 'TaskList' || key === 'Script' || key === 'Tools'){
                 continue
                 continue
@@ -152,9 +173,9 @@ Item{
             const groupData = classify(menu[key], data)
             const groupData = classify(menu[key], data)
             create_group(key, groupData)
             create_group(key, groupData)
         }
         }
-
     }
     }
 
 
+
     // 分类对每一个任务组,
     // 分类对每一个任务组,
     // 第一个参数是这个菜单组的所有, 如["Script", "Restart", "GlobalGame"]
     // 第一个参数是这个菜单组的所有, 如["Script", "Restart", "GlobalGame"]
     // 第二个参数是整个的数据
     // 第二个参数是整个的数据

+ 47 - 20
module/server/app.py

@@ -1,19 +1,33 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
+from contextlib import asynccontextmanager
+
 import argparse
 import argparse
-from fastapi import FastAPI
+from starlette import status
+from starlette.responses import JSONResponse
+from fastapi import FastAPI, Request
 from fastapi.middleware.cors import CORSMiddleware
 from fastapi.middleware.cors import CORSMiddleware
 
 
 from module.logger import logger
 from module.logger import logger
-
 from module.server.home_router import home_app
 from module.server.home_router import home_app
 from module.server.script_router import script_app
 from module.server.script_router import script_app
+from module.server.setting import State
+from module.server.main_manager import mm
+
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+    await on_startup()
+    yield
+    await on_shutdown()
 
 
 app = FastAPI(
 app = FastAPI(
     title='OAS',
     title='OAS',
     description='OAS web service',
     description='OAS web service',
     version='0.0.0',
     version='0.0.0',
+    lifespan=lifespan,
 )
 )
 
 
 app.add_middleware(
 app.add_middleware(
@@ -27,30 +41,33 @@ app.add_middleware(
 app.include_router(home_app)
 app.include_router(home_app)
 app.include_router(script_app)
 app.include_router(script_app)
 
 
-@app.on_event("startup")
-async def startup_event():
-    logger.info('OAS web service startup done')
-    pass
-
-@app.on_event("shutdown")
-async def shutdown_event():
-    logger.info('OAS web service shutdown done')
-
-
-
-
-
-
-
-
-
 
 
+async def on_startup():
+    """
+    app.state 的生命周期在定义app的时候就有了
+    :return:
+    """
+    logger.info('OAS web service startup done')
+    if app.state.script_instances:
+        await mm.restart_processes(app.state.script_instances)
 
 
 
 
+async def on_shutdown():
+    logger.info('OAS web service shutdown done')
 
 
 
 
+@app.exception_handler(Exception)
+async def global_exception_handler(request: Request, exc: Exception):
+    logger.error(f"Internal Server Error: ", exc_info=True)
 
 
+    message = ', '.join(str(arg) for arg in exc.args) if exc.args else str(exc)
 
 
+    return JSONResponse(
+        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+        content={
+            'message': message
+        },
+    )
 
 
 
 
 def fastapi_app():
 def fastapi_app():
@@ -70,6 +87,16 @@ def fastapi_app():
         help="Run OAS by config names on startup",
         help="Run OAS by config names on startup",
     )
     )
     args, _ = parser.parse_known_args()
     args, _ = parser.parse_known_args()
-
+    # ------------------------------------------------------------------------------------------------------------------
+
+    runs = None
+    if args.run:
+        runs = args.run
+    elif State.deploy_config.Run:
+        # TODO: refactor poor_yaml_read() to support list
+        tmp = State.deploy_config.Run.split(",")
+        runs = [l.strip(" ['\"]") for l in tmp if len(l)]
+    # ------------------------------------------------------------------------------------------------------------------
+    app.state.script_instances = runs
 
 
     return app
     return app

+ 10 - 0
module/server/home_router.py

@@ -84,3 +84,13 @@ async def chinese_translate(data: dict = Body(...)):
     except Exception as e:
     except Exception as e:
         logger.error(e)
         logger.error(e)
     return True
     return True
+
+
+@home_app.get('/additional_translate')
+async def additional_translate() -> dict:
+    try:
+        data = I18n.load_additions()
+        return data
+    except Exception as e:
+        logger.error(e)
+    return {}

+ 18 - 2
module/server/i18n.py

@@ -2,7 +2,22 @@ import json
 from pathlib import Path
 from pathlib import Path
 
 
 
 
-class I18n:
+class Addition:
+    @classmethod
+    def load_additions(cls) -> dict:
+        result = {}
+        files: str = ['en-US', 'zh-CN']
+        for file in files:
+            file_path = Path.cwd() / 'assets' / 'i18n' / f'{file}.json'
+            result[file] = {}
+            if not file_path.exists():
+                continue
+            with open(str(file_path), 'r', encoding='utf-8') as f:
+                result[file] = json.load(f)
+        return result
+
+
+class I18n(Addition):
     file_zh_cn = Path.cwd() / 'module' / 'config' / 'i18n' / 'zh-CN.json'
     file_zh_cn = Path.cwd() / 'module' / 'config' / 'i18n' / 'zh-CN.json'
 
 
     @classmethod
     @classmethod
@@ -24,5 +39,6 @@ class I18n:
         with open(str(I18n.file_zh_cn), 'r', encoding='utf-8') as f:
         with open(str(I18n.file_zh_cn), 'r', encoding='utf-8') as f:
             return json.load(f)
             return json.load(f)
 
 
+
 if __name__ == '__main__':
 if __name__ == '__main__':
-    print(I18n.load_zh_cn())
+    print(I18n.load_zh_cn())

+ 16 - 3
module/server/main_manager.py

@@ -42,6 +42,10 @@ class MainManager(ConfigManager):
     #         self.config_cache = Config(config_name)
     #         self.config_cache = Config(config_name)
     #     return self.config_cache
     #     return self.config_cache
 
 
+    @staticmethod
+    def config_cache(name: str) -> Config:
+        return Config(name)
+
     def add_script_file(self, file_name: str):
     def add_script_file(self, file_name: str):
         # 当你添加了新的脚本文件后,需要添加缓存的列表
         # 当你添加了新的脚本文件后,需要添加缓存的列表
         if file_name in self._all_script_files:
         if file_name in self._all_script_files:
@@ -95,7 +99,16 @@ class MainManager(ConfigManager):
                     tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
                     tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
                                                                     name=coroutine_log_name)
                                                                     name=coroutine_log_name)
 
 
-    @staticmethod
-    def config_cache(name: str) -> Config:
-        return Config(name)
+    async def restart_processes(self, script_instances: list[str]):
+        for instance in script_instances:
+            logger.info(f'Restart script {instance}')
+            if instance not in self.script_process:
+                try:
+                    self.script_process[instance] = ScriptProcess(instance)
+                except FileNotFoundError:
+                    logger.error(f'{instance} file not found')
+                    continue
+            await self.script_process[instance].start()
+
 
 
+mm = MainManager()

+ 21 - 6
module/server/script_process.py

@@ -2,33 +2,36 @@
 # @author runhey
 # @author runhey
 # 脚本进程
 # 脚本进程
 # github https://github.com/runhey
 # github https://github.com/runhey
+import sys, os
+import signal
 import multiprocessing
 import multiprocessing
 from asyncio import QueueEmpty, CancelledError, sleep
 from asyncio import QueueEmpty, CancelledError, sleep
 from enum import Enum
 from enum import Enum
 
 
 from module.logger import logger
 from module.logger import logger
-
+from module.server.config_manager import ConfigManager
 from module.server.script_websocket import ScriptWSManager
 from module.server.script_websocket import ScriptWSManager
 
 
+
 class ScriptState(int, Enum):
 class ScriptState(int, Enum):
     INACTIVE = 0
     INACTIVE = 0
     RUNNING = 1
     RUNNING = 1
     WARNING = 2
     WARNING = 2
     UPDATING = 3
     UPDATING = 3
 
 
+
 class ScriptProcess(ScriptWSManager):
 class ScriptProcess(ScriptWSManager):
 
 
     def __init__(self, config_name: str) -> None:
     def __init__(self, config_name: str) -> None:
         super().__init__()
         super().__init__()
+        if config_name not in ConfigManager.all_script_files():
+            raise FileNotFoundError(f'{config_name}.json not found')
         self.config_name = config_name  # config_name
         self.config_name = config_name  # config_name
         self.log_pipe_out, self.log_pipe_in = multiprocessing.Pipe(False)
         self.log_pipe_out, self.log_pipe_in = multiprocessing.Pipe(False)
         self.state_queue = multiprocessing.Queue()
         self.state_queue = multiprocessing.Queue()
         self.state: ScriptState = ScriptState.INACTIVE
         self.state: ScriptState = ScriptState.INACTIVE
         self._process = None
         self._process = None
 
 
-
-
-
     async def start(self):
     async def start(self):
         self.state = ScriptState.RUNNING
         self.state = ScriptState.RUNNING
         await self.broadcast_state({"state": self.state})
         await self.broadcast_state({"state": self.state})
@@ -40,10 +43,10 @@ class ScriptProcess(ScriptWSManager):
         self._process = multiprocessing.Process(target=func,
         self._process = multiprocessing.Process(target=func,
                                                 args=(self.config_name, self.state_queue, self.log_pipe_in,),
                                                 args=(self.config_name, self.state_queue, self.log_pipe_in,),
                                                 name=self.config_name,
                                                 name=self.config_name,
-                                                daemon=True)
+                                                daemon=True
+                                                )
         self._process.start()
         self._process.start()
 
 
-
     async def stop(self):
     async def stop(self):
         self.state = ScriptState.INACTIVE
         self.state = ScriptState.INACTIVE
         await self.broadcast_state({"state": self.state})
         await self.broadcast_state({"state": self.state})
@@ -54,6 +57,10 @@ class ScriptProcess(ScriptWSManager):
             logger.warning(f'Script {self.config_name} is not running')
             logger.warning(f'Script {self.config_name} is not running')
             return
             return
         self._process.terminate()
         self._process.terminate()
+        self._process.join(timeout=0.7)
+        if self._process.is_alive():
+            logger.error(f'Script {self.config_name} subprocess terminate failed')
+            self._process.kill()
         self._process = None
         self._process = None
 
 
     async def coroutine_broadcast_state(self):
     async def coroutine_broadcast_state(self):
@@ -114,6 +121,14 @@ class ScriptProcess(ScriptWSManager):
 
 
 
 
 def func(config: str, state_queue: multiprocessing.Queue, log_pipe_in) -> None:
 def func(config: str, state_queue: multiprocessing.Queue, log_pipe_in) -> None:
+    def signal_handler(signum, frame):
+        logger.info(f'Script {config} received signal {signum}, exiting gracefully')
+        log_pipe_in.close()
+        state_queue.close()
+        sys.exit(0)
+
+    signal.signal(signal.SIGTERM, signal_handler)
+    signal.signal(signal.SIGINT, signal_handler)
 
 
     def start_log() -> None:
     def start_log() -> None:
         try:
         try:

+ 23 - 3
module/server/script_router.py

@@ -6,17 +6,17 @@ from fastapi import APIRouter, HTTPException
 from fastapi.responses import StreamingResponse
 from fastapi.responses import StreamingResponse
 from fastapi import WebSocket, WebSocketDisconnect
 from fastapi import WebSocket, WebSocketDisconnect
 from datetime import datetime
 from datetime import datetime
-from module.config.config import Config
+from module.config.utils import convert_to_underscore
 
 
 from module.logger import logger
 from module.logger import logger
-from module.server.main_manager import MainManager
+from module.server.main_manager import mm
 from module.server.script_process import ScriptProcess, ScriptState
 from module.server.script_process import ScriptProcess, ScriptState
 
 
 from tasks.Component.config_base import TimeDelta
 from tasks.Component.config_base import TimeDelta
 
 
 
 
 script_app = APIRouter()
 script_app = APIRouter()
-mm = MainManager()
+
 
 
 @script_app.get('/test')
 @script_app.get('/test')
 async def script_test():
 async def script_test():
@@ -81,6 +81,26 @@ async def config_delete(name: str = ''):
     return True
     return True
 
 
 
 
+@script_app.put('/config/task/copy')
+async def task_copy(task_name: str, dest_config_name: str, source_config_name: str):
+    if dest_config_name not in mm.script_process or source_config_name not in mm.script_process:
+        return False
+    source_task = getattr(mm.config_cache(source_config_name).model, convert_to_underscore(task_name), None)
+    if source_task is None:
+        return False
+    return mm.config_cache(dest_config_name).model.copy_script_task(task_name, source_task)
+
+
+@script_app.put('/config/task/group/copy')
+async def task_group_copy(task_name: str, group_name: str, dest_config_name: str, source_config_name: str):
+    if dest_config_name not in mm.script_process or source_config_name not in mm.script_process:
+        return False
+    source_task = getattr(mm.config_cache(source_config_name).model, convert_to_underscore(task_name), None)
+    if source_task is None:
+        return False
+    return mm.config_cache(dest_config_name).model.copy_task_group(task_name, group_name, source_task)
+
+
 # ---------------------------------   脚本实例管理   ----------------------------------
 # ---------------------------------   脚本实例管理   ----------------------------------
 @script_app.get('/{script_name}/start')
 @script_app.get('/{script_name}/start')
 async def script_start(script_name: str):
 async def script_start(script_name: str):

+ 12 - 7
module/server/script_websocket.py

@@ -19,27 +19,32 @@ class ScriptWSManager:
         try:
         try:
             # 给前端发送最后一次关闭信号
             # 给前端发送最后一次关闭信号
             await ws.close()
             await ws.close()
-        except RuntimeError:
-            pass
+        except RuntimeError as e:
+            print(e)
 
 
     async def broadcast(self, message: str):
     async def broadcast(self, message: str):
         # 广播消息
         # 广播消息
         for connection in self.active_connections:
         for connection in self.active_connections:
-            await connection.send_text(message)
+            try:
+                await connection.send_text(message)
+            except RuntimeError:
+                await self.disconnect(connection)
 
 
     async def broadcast_state(self, data: dict):
     async def broadcast_state(self, data: dict):
         # 广播自身的状态
         # 广播自身的状态
         for connection in self.active_connections:
         for connection in self.active_connections:
-            await connection.send_json(data)
+            try:
+                await connection.send_json(data)
+            except RuntimeError:
+                await self.disconnect(connection)
 
 
     async def broadcast_log(self, log: str):
     async def broadcast_log(self, log: str):
         # 广播日志
         # 广播日志
         for connection in self.active_connections:
         for connection in self.active_connections:
             try:
             try:
                 await connection.send_text(log)
                 await connection.send_text(log)
-            except RuntimeError as e:
-                print(e)
-                self.active_connections.remove(connection)
+            except RuntimeError:
+                await self.disconnect(connection)
 
 
 
 
 
 

+ 1 - 6
module/server/updater.py

@@ -5,7 +5,6 @@ import time
 import requests
 import requests
 from typing import Generator, List, Tuple
 from typing import Generator, List, Tuple
 
 
-
 from deploy.config import ExecutionError
 from deploy.config import ExecutionError
 from deploy.git import GitManager
 from deploy.git import GitManager
 from deploy.pip import PipManager
 from deploy.pip import PipManager
@@ -64,11 +63,7 @@ class Updater(DeployConfig, GitManager, PipManager):
             return logs
             return logs
 
 
     def current_branch(self) -> str:
     def current_branch(self) -> str:
-        log : str = subprocess.run(
-            'git branch --show-current', capture_output=True, text=True, encoding="utf8", shell=True
-        ).stdout
-        log = log.replace('\n', '')
-        return log
+        return self.Branch
 
 
     def current_commit(self) -> str:
     def current_commit(self) -> str:
         return self.get_commit()
         return self.get_commit()

+ 1 - 1
requirements-in.txt

@@ -17,7 +17,7 @@ cn2an==0.5.23
 # Web
 # Web
 paho-mqtt==1.6.1
 paho-mqtt==1.6.1
 fastapi==0.104.1
 fastapi==0.104.1
-uvicorn==0.23.2
+uvicorn==0.38.0
 websockets==11.0.3
 websockets==11.0.3
 zerorpc==0.6.3
 zerorpc==0.6.3
 pydantic==2.10.0
 pydantic==2.10.0

+ 1 - 2
requirements.txt

@@ -5,7 +5,6 @@
 #    pip-compile --annotation-style=line --output-file=requirements.txt requirements-in.txt
 #    pip-compile --annotation-style=line --output-file=requirements.txt requirements-in.txt
 #
 #
 
 
-
 adbutils==0.11.0          # via -r requirements-in.txt, uiautomator2
 adbutils==0.11.0          # via -r requirements-in.txt, uiautomator2
 annotated-types==0.7.0    # via pydantic
 annotated-types==0.7.0    # via pydantic
 anyio==3.7.1              # via fastapi, starlette
 anyio==3.7.1              # via fastapi, starlette
@@ -80,7 +79,7 @@ typing-extensions==4.12.2  # via fastapi, pydantic, pydantic-core, uvicorn
 uiautomator2==2.16.17     # via -r requirements-in.txt
 uiautomator2==2.16.17     # via -r requirements-in.txt
 uiautomator2cache==0.3.0.1  # via -r requirements-in.txt
 uiautomator2cache==0.3.0.1  # via -r requirements-in.txt
 urllib3==2.1.0            # via requests
 urllib3==2.1.0            # via requests
-uvicorn==0.23.2           # via -r requirements-in.txt
+uvicorn==0.38.0           # via -r requirements-in.txt
 websockets==11.0.3        # via -r requirements-in.txt
 websockets==11.0.3        # via -r requirements-in.txt
 whichcraft==0.6.1         # via adbutils, uiautomator2
 whichcraft==0.6.1         # via adbutils, uiautomator2
 wrapt==1.15.0             # via -r requirements-in.txt, deprecated
 wrapt==1.15.0             # via -r requirements-in.txt, deprecated

+ 12 - 4
script.py

@@ -29,12 +29,13 @@ from module.config.utils import convert_to_underscore
 from module.config.config import Config
 from module.config.config import Config
 from module.config.config_model import ConfigModel
 from module.config.config_model import ConfigModel
 from module.device.device import Device
 from module.device.device import Device
+from module.device.env import IS_WINDOWS
 from module.base.utils import load_module
 from module.base.utils import load_module
 from module.base.decorator import del_cached_property
 from module.base.decorator import del_cached_property
 from module.logger import logger
 from module.logger import logger
 from module.exception import *
 from module.exception import *
 from module.server.i18n import I18n
 from module.server.i18n import I18n
-from module.device.platform2.platform_windows import minimize_by_name,show_window_by_name
+
 
 
 
 
 _log_switch_lock = threading.Lock()#线程锁
 _log_switch_lock = threading.Lock()#线程锁
@@ -100,8 +101,11 @@ class Script:
         if self.config.script.error.save_error:
         if self.config.script.error.save_error:
             if not os.path.exists('./log/error'):
             if not os.path.exists('./log/error'):
                 os.mkdir('./log/error')
                 os.mkdir('./log/error')
-            folder = f'./log/error/{int(time.time() * 1000)}'
+            folder_name = str(int(time.time() * 1000))
+            folder = f'./log/error/{folder_name}'
             logger.warning(f'Saving error: {folder}')
             logger.warning(f'Saving error: {folder}')
+            logger.info('保存详细错误的日志和截图到路径:')
+            logger.info(f'{str( Path.cwd() / "log" / "error" / folder_name)}')
             os.mkdir(folder)
             os.mkdir(folder)
             for data in self.device.screenshot_deque:
             for data in self.device.screenshot_deque:
                 image_time = datetime.strftime(data['time'], '%Y-%m-%d_%H-%M-%S-%f')
                 image_time = datetime.strftime(data['time'], '%Y-%m-%d_%H-%M-%S-%f')
@@ -355,6 +359,9 @@ class Script:
         # 处理御魂溢出
         # 处理御魂溢出
         from tasks.Utils.post_diagnotor import PostDiagnotor, AnalyzeType
         from tasks.Utils.post_diagnotor import PostDiagnotor, AnalyzeType
         image = getattr(self.device, 'image', None)
         image = getattr(self.device, 'image', None)
+        # image为None则不做处理
+        if image is None:
+            return
         analyse_type = PostDiagnotor().handle(e=e, command=command, image=image)
         analyse_type = PostDiagnotor().handle(e=e, command=command, image=image)
         if analyse_type == AnalyzeType.SoulOverflow:
         if analyse_type == AnalyzeType.SoulOverflow:
             self.config.task_call('SoulsTidy')
             self.config.task_call('SoulsTidy')
@@ -442,7 +449,8 @@ class Script:
         self.config.model.running_task = ''
         self.config.model.running_task = ''
 
 
         # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
         # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
-        if not self.config.script.device.run_background_only:
+        if not self.config.script.device.run_background_only and IS_WINDOWS:
+            from module.device.platform2.platform_windows import minimize_by_name, show_window_by_name
             target_window_name = self.config.script.device.handle  # 在这里输入你的具体窗口名称
             target_window_name = self.config.script.device.handle  # 在这里输入你的具体窗口名称
             if self.config.script.device.emulator_window_minimize:
             if self.config.script.device.emulator_window_minimize:
                 minimize_by_name(target_window_name)
                 minimize_by_name(target_window_name)
@@ -539,5 +547,5 @@ class Script:
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    script = Script("oas2")
+    script = Script("oas1")
     script.loop()
     script.loop()

+ 2 - 2
tasks/AbyssShadows/config.py

@@ -5,8 +5,8 @@
 # github    https://github.com/roarhill/oas
 # github    https://github.com/roarhill/oas
 
 
 from pydantic import BaseModel, Field
 from pydantic import BaseModel, Field
-from pygments.lexer import default
-from scripts.regsetup import description
+# from pygments.lexer import default
+# from scripts.regsetup import description
 from sympy.testing.pytest import Failed
 from sympy.testing.pytest import Failed
 
 
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig

BIN
tasks/ActivityShikigami/0110/0110_c_confirm1.png


BIN
tasks/ActivityShikigami/0110/0110_n_battle.png


BIN
tasks/ActivityShikigami/0110/0110_n_confirm.png


+ 0 - 26
tasks/ActivityShikigami/0110/click.json

@@ -1,26 +0,0 @@
-[
-  {
-    "itemName": "click1",
-    "roiFront": "120,138,130,75",
-    "roiBack": "120,138,130,75",
-    "description": "description"
-  },
-  {
-    "itemName": "click2",
-    "roiFront": "121,234,125,81",
-    "roiBack": "121,234,125,81",
-    "description": "description"
-  },
-  {
-    "itemName": "click3",
-    "roiFront": "126,337,118,77",
-    "roiBack": "126,337,118,77",
-    "description": "description"
-  },
-  {
-    "itemName": "click4",
-    "roiFront": "124,438,126,77",
-    "roiBack": "124,438,126,77",
-    "description": "description"
-  }
-]

+ 0 - 29
tasks/ActivityShikigami/0110/image.json

@@ -1,29 +0,0 @@
-[
-  {
-    "itemName": "n_battle",
-    "imageName": "0110_n_battle.png",
-    "roiFront": "131,164,86,86",
-    "roiBack": "119,50,1075,635",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "description"
-  },
-  {
-    "itemName": "n_confirm",
-    "imageName": "0110_n_confirm.png",
-    "roiFront": "670,402,176,63",
-    "roiBack": "670,402,176,63",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "description"
-  },
-  {
-    "itemName": "c_confirm1",
-    "imageName": "0110_c_confirm1.png",
-    "roiFront": "560,341,37,38",
-    "roiBack": "560,341,37,38",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "description"
-  }
-]

+ 180 - 0
tasks/ActivityShikigami/README.md

@@ -0,0 +1,180 @@
+## 这里是约定哪些是需要更新的     ./script_test.py 是对应的测试
+
+
+
+## 关于页面导航(`./as/page.json`文件)
+
+#### 图片 `shi` 表示进入到活动的主页面,截图的时候往上截图一点,因为快结束的时候图片下方会显示还有多少小时结束
+
+![image-20251220103009134](https://runhey-img-stg1.oss-cn-chengdu.aliyuncs.com/img3/202512201030265.png)
+
+#### 图片`to_battle_main` 和 `to_battle_boss` 分别表示进入默认的挑战界面和boss挑战界面
+
+![image-20251220103500219](https://runhey-img-stg1.oss-cn-chengdu.aliyuncs.com/img3/202512201035354.png)
+
+#### 图片`check_battle_main` 表示到达了这个默认战斗界面       |  `battle_main_to_records`表示从这里进入式神录来切换御魂
+
+#### 图片`check_battle_boss`  和 `battle_boss_to_records` 类似的
+
+![image-20251220104003594](https://runhey-img-stg1.oss-cn-chengdu.aliyuncs.com/img3/202512201040758.png)
+
+#### 可能需要更新的如 `back_green`、 `red_exit` 和 `skip_button`  这些表示退出的时候碰到的时候会出现的
+
+#### OAS 内部有一个专门的类来存放通用的图片。  路径在`./tasks/GlobalGame/ui`  有需要直接使用
+
+![image-20251220104718877](https://runhey-img-stg1.oss-cn-chengdu.aliyuncs.com/img3/202512201047907.png)
+
+
+
+## 关于战斗更新 (`./fire/ocr.json`文件)
+
+#### OCR `remain_ap`  表示体力模式下剩余多少次数  `fire` 表示点击挑战
+
+![image-20251220111306772](https://runhey-img-stg1.oss-cn-chengdu.aliyuncs.com/img3/202512201113931.png)
+
+活动币模式下 `remain_pass`  和 boss 模式下也是类似
+
+![image-20251220111505769](https://runhey-img-stg1.oss-cn-chengdu.aliyuncs.com/img3/202512201115927.png)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

BIN
tasks/ActivityShikigami/as/as_act_map_switch.png


BIN
tasks/ActivityShikigami/as/as_antivity_win.png


BIN
tasks/ActivityShikigami/as/as_battle.png


BIN
tasks/ActivityShikigami/as/as_battle_1.png


BIN
tasks/ActivityShikigami/as/as_battle_main_to_records.png


BIN
tasks/ActivityShikigami/as/as_battle_org.png


BIN
tasks/ActivityShikigami/as/as_boss.png


BIN
tasks/ActivityShikigami/as/as_buff_box_1_empty.png


BIN
tasks/ActivityShikigami/as/as_buff_box_2_empty.png


BIN
tasks/ActivityShikigami/as/as_buff_change_button.png


BIN
tasks/ActivityShikigami/as/as_buff_down.png


BIN
tasks/ActivityShikigami/as/as_buff_switch.png


BIN
tasks/ActivityShikigami/as/as_buff_up.png


BIN
tasks/ActivityShikigami/as/as_check_act_list_climb_act.png


BIN
tasks/ActivityShikigami/as/as_check_battle_2.png


BIN
tasks/ActivityShikigami/as/as_check_battle_main.png


BIN
tasks/ActivityShikigami/as/as_check_buff.png


BIN
tasks/ActivityShikigami/as/as_drum.png


BIN
tasks/ActivityShikigami/as/as_entry_activity.png


BIN
tasks/ActivityShikigami/as/as_lock.png


BIN
tasks/ActivityShikigami/as/as_new.png


BIN
tasks/ActivityShikigami/as/as_pass_act_locat.png


BIN
tasks/ActivityShikigami/as/as_red_exit_2.png


BIN
tasks/ActivityShikigami/as/as_shi.png


BIN
tasks/ActivityShikigami/as/as_to_battle_boss.png


BIN
tasks/ActivityShikigami/as/as_to_battle_main.png


+ 7 - 49
tasks/ActivityShikigami/as/click.json

@@ -1,26 +1,26 @@
 [
 [
   {
   {
     "itemName": "random_left",
     "itemName": "random_left",
-    "roiFront": "21,23,237,599",
-    "roiBack": "21,23,237,599",
+    "roiFront": "17,69,132,599",
+    "roiBack": "17,70,137,599",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "random_right",
     "itemName": "random_right",
-    "roiFront": "1047,55,218,638",
-    "roiBack": "1047,55,218,638",
+    "roiFront": "1133,55,131,638",
+    "roiBack": "1131,55,133,638",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "random_top",
     "itemName": "random_top",
-    "roiFront": "85,46,1159,101",
+    "roiFront": "84,49,1159,93",
     "roiBack": "85,46,1159,101",
     "roiBack": "85,46,1159,101",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "random_bottom",
     "itemName": "random_bottom",
-    "roiFront": "182,539,1063,100",
-    "roiBack": "182,539,1063,100",
+    "roiFront": "179,577,972,100",
+    "roiBack": "179,579,972,100",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
@@ -28,47 +28,5 @@
     "roiFront": "42,94,1207,543",
     "roiFront": "42,94,1207,543",
     "roiBack": "42,94,1207,543",
     "roiBack": "42,94,1207,543",
     "description": "description"
     "description": "description"
-  },
-  {
-    "itemName": "buff_1_up",
-    "roiFront": "204,626,134,39",
-    "roiBack": "204,626,134,39",
-    "description": "替换buff1"
-  },
-  {
-    "itemName": "buff_2_up",
-    "roiFront": "414,625,134,39",
-    "roiBack": "414,625,134,39",
-    "description": "替换buff2"
-  },
-  {
-    "itemName": "buff_3_up",
-    "roiFront": "619,625,134,39",
-    "roiBack": "619,625,134,39",
-    "description": "替换buff3"
-  },
-  {
-    "itemName": "buff_4_up",
-    "roiFront": "831,625,134,39",
-    "roiBack": "831,625,134,39",
-    "description": "替换buff4"
-  },
-  {
-    "itemName": "buff_5_up",
-    "roiFront": "1043,624,134,39",
-    "roiBack": "1043,624,134,39",
-    "description": "替换buff5"
-  },
-  {
-    "itemName": "buff_1_box",
-    "roiFront": "333,338,70,72",
-    "roiBack": "333,338,70,72",
-    "description": "上阵buff_1位置"
-  },
-  {
-    "itemName": "buff_2_box",
-    "roiFront": "877,220,59,62",
-    "roiBack": "877,220,59,62",
-    "description": "上阵buff_2位置"
   }
   }
 ]
 ]

+ 3 - 201
tasks/ActivityShikigami/as/image.json

@@ -1,54 +1,9 @@
 [
 [
-  {
-    "itemName": "shi",
-    "imageName": "as_shi.png",
-    "roiFront": "1183,319,47,38",
-    "roiBack": "1164,134,83,318",
-    "method": "Template matching",
-    "threshold": 0.7,
-    "description": "进入活动"
-  },
-  {
-    "itemName": "back_green",
-    "imageName": "as_back_green.png",
-    "roiFront": "27,19,34,38",
-    "roiBack": "2,1,170,75",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "左上角返回"
-  },
-  {
-    "itemName": "battle",
-    "imageName": "as_battle.png",
-    "roiFront": "813,254,35,135",
-    "roiBack": "754,140,154,315",
-    "method": "Template matching",
-    "threshold": 0.7,
-    "description": "征伐斗场"
-  },
-  {
-    "itemName": "battle_1",
-    "imageName": "as_battle_1.png",
-    "roiFront": "541,197,149,26",
-    "roiBack": "506,622,273,96",
-    "method": "Template matching",
-    "threshold": 0.7,
-    "description": "进入爬塔1"
-  },
-  {
-    "itemName": "drum",
-    "imageName": "as_drum.png",
-    "roiFront": "327,627,145,28",
-    "roiBack": "256,462,301,232",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "归鹿之途"
-  },
   {
   {
     "itemName": "lock",
     "itemName": "lock",
     "imageName": "as_lock.png",
     "imageName": "as_lock.png",
-    "roiFront": "884,648,28,25",
-    "roiBack": "761,613,255,76",
+    "roiFront": "825,657,28,25",
+    "roiBack": "739,613,276,85",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.5,
     "threshold": 0.5,
     "description": "上锁图标"
     "description": "上锁图标"
@@ -57,7 +12,7 @@
     "itemName": "unlock",
     "itemName": "unlock",
     "imageName": "as_unlock.png",
     "imageName": "as_unlock.png",
     "roiFront": "884,648,28,25",
     "roiFront": "884,648,28,25",
-    "roiBack": "758,607,242,85",
+    "roiBack": "733,607,266,95",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.5,
     "threshold": 0.5,
     "description": "还未上锁图片"
     "description": "还未上锁图片"
@@ -107,24 +62,6 @@
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "增加到最大"
     "description": "增加到最大"
   },
   },
-  {
-    "itemName": "skip_button",
-    "imageName": "as_skip_button.png",
-    "roiFront": "1159,37,51,22",
-    "roiBack": "1141,27,86,43",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "右上跳过按钮"
-  },
-  {
-    "itemName": "red_exit",
-    "imageName": "as_red_exit.png",
-    "roiFront": "1162,96,39,38",
-    "roiBack": "1120,49,110,135",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "红色退出"
-  },
   {
   {
     "itemName": "toggle_button",
     "itemName": "toggle_button",
     "imageName": "as_toggle_button.png",
     "imageName": "as_toggle_button.png",
@@ -133,140 +70,5 @@
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "description"
     "description": "description"
-  },
-  {
-    "itemName": "boss",
-    "imageName": "as_boss.png",
-    "roiFront": "165,339,33,132",
-    "roiBack": "103,218,160,355",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "爬塔进入首领战"
-  },
-  {
-    "itemName": "check_boss",
-    "imageName": "as_check_boss.png",
-    "roiFront": "87,18,126,37",
-    "roiBack": "63,0,172,81",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "爬塔boss战页面检查图像"
-  },
-  {
-    "itemName": "check_battle_2",
-    "imageName": "as_check_battle_2.png",
-    "roiFront": "22,632,61,69",
-    "roiBack": "1,601,109,117",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "爬塔活动副页检查标志"
-  },
-  {
-    "itemName": "red_exit_2",
-    "imageName": "as_red_exit_2.png",
-    "roiFront": "1097,177,46,45",
-    "roiBack": "931,128,237,164",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "爬塔活动页面的红色退出"
-  },
-  {
-    "itemName": "buff_down",
-    "imageName": "as_buff_down.png",
-    "roiFront": "428,625,100,37",
-    "roiBack": "177,600,1040,98",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "卸载buff"
-  },
-  {
-    "itemName": "buff_change_button",
-    "imageName": "as_buff_change_button.png",
-    "roiFront": "491,604,48,46",
-    "roiBack": "439,574,197,108",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "切换buff按钮"
-  },
-  {
-    "itemName": "buff_box_1_empty",
-    "imageName": "as_buff_box_1_empty.png",
-    "roiFront": "342,345,50,59",
-    "roiBack": "317,322,100,100",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "buff容器1为空"
-  },
-  {
-    "itemName": "buff_box_2_empty",
-    "imageName": "as_buff_box_2_empty.png",
-    "roiFront": "883,224,49,54",
-    "roiBack": "854,195,107,105",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "buff容器2为空"
-  },
-  {
-    "itemName": "buff_up",
-    "imageName": "as_buff_up.png",
-    "roiFront": "419,624,120,41",
-    "roiBack": "176,576,1025,142",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "装配buff"
-  },
-  {
-    "itemName": "buff_switch",
-    "imageName": "as_buff_switch.png",
-    "roiFront": "640,624,100,39",
-    "roiBack": "180,601,1026,100",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "buff切换"
-  },
-  {
-    "itemName": "check_buff",
-    "imageName": "as_check_buff.png",
-    "roiFront": "91,12,130,47",
-    "roiBack": "77,0,156,83",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "爬塔活动buff页"
-  },
-  {
-    "itemName": "entry_activity",
-    "imageName": "as_entry_activity.png",
-    "roiFront": "567,258,46,42",
-    "roiBack": "254,56,774,524",
-    "method": "Template matching",
-    "threshold": 0.5,
-    "description": "进入门票活动"
-  },
-  {
-    "itemName": "check_act_list_climb_act",
-    "imageName": "as_check_act_list_climb_act.png",
-    "roiFront": "538,194,497,193",
-    "roiBack": "415,67,773,390",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "活动列表页爬塔活动"
-  },
-  {
-    "itemName": "act_map_switch",
-    "imageName": "as_act_map_switch.png",
-    "roiFront": "1196,303,59,48",
-    "roiBack": "1174,263,104,118",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "活动地图切换"
-  },
-  {
-    "itemName": "pass_act_locat",
-    "imageName": "as_pass_act_locat.png",
-    "roiFront": "1214,395,29,31",
-    "roiBack": "1179,373,100,86",
-    "method": "Template matching",
-    "threshold": 0.8,
-    "description": "门票活动定位"
   }
   }
 ]
 ]

+ 83 - 0
tasks/ActivityShikigami/as/pages.json

@@ -0,0 +1,83 @@
+[
+  {
+    "itemName": "shi",
+    "imageName": "as_shi.png",
+    "roiFront": "1182,391,47,29",
+    "roiBack": "1164,134,83,318",
+    "method": "Template matching",
+    "threshold": 0.7,
+    "description": "进入活动"
+  },
+  {
+    "itemName": "back_green",
+    "imageName": "as_back_green.png",
+    "roiFront": "27,19,34,38",
+    "roiBack": "2,1,170,75",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "左上角返回"
+  },
+  {
+    "itemName": "skip_button",
+    "imageName": "as_skip_button.png",
+    "roiFront": "1159,37,51,22",
+    "roiBack": "1141,27,86,43",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "右上跳过按钮"
+  },
+  {
+    "itemName": "red_exit",
+    "imageName": "as_red_exit.png",
+    "roiFront": "1162,96,39,38",
+    "roiBack": "1120,49,110,135",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "红色退出"
+  },
+  {
+    "itemName": "to_battle_main",
+    "imageName": "as_to_battle_main.png",
+    "roiFront": "646,121,39,176",
+    "roiBack": "606,91,100,241",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "进入主要的战斗界面"
+  },
+  {
+    "itemName": "to_battle_boss",
+    "imageName": "as_to_battle_boss.png",
+    "roiFront": "931,217,37,173",
+    "roiBack": "909,198,100,219",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "点击进入boss战斗页面"
+  },
+  {
+    "itemName": "check_battle_main",
+    "imageName": "as_check_battle_main.png",
+    "roiFront": "30,130,75,46",
+    "roiBack": "17,104,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "check_battle_boss",
+    "imageName": "as_check_battle_boss.png",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "battle_main_to_records",
+    "imageName": "as_battle_main_to_records.png",
+    "roiFront": "1208,112,39,42",
+    "roiBack": "1171,86,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "从main进入到式神录"
+  }
+]

+ 62 - 88
tasks/ActivityShikigami/assets.py

@@ -12,66 +12,22 @@ class ActivityShikigamiAssets:
 
 
 	# Click Rule Assets
 	# Click Rule Assets
 	# description 
 	# description 
-	C_CLICK1 = RuleClick(roi_front=(120,138,130,75), roi_back=(120,138,130,75), name="click1")
+	C_RANDOM_LEFT = RuleClick(roi_front=(17,69,132,599), roi_back=(17,70,137,599), name="random_left")
 	# description 
 	# description 
-	C_CLICK2 = RuleClick(roi_front=(121,234,125,81), roi_back=(121,234,125,81), name="click2")
+	C_RANDOM_RIGHT = RuleClick(roi_front=(1133,55,131,638), roi_back=(1131,55,133,638), name="random_right")
 	# description 
 	# description 
-	C_CLICK3 = RuleClick(roi_front=(126,337,118,77), roi_back=(126,337,118,77), name="click3")
+	C_RANDOM_TOP = RuleClick(roi_front=(84,49,1159,93), roi_back=(85,46,1159,101), name="random_top")
 	# description 
 	# description 
-	C_CLICK4 = RuleClick(roi_front=(124,438,126,77), roi_back=(124,438,126,77), name="click4")
-
-
-	# Image Rule Assets
-	# description 
-	I_N_BATTLE = RuleImage(roi_front=(131,164,86,86), roi_back=(119,50,1075,635), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/0110/0110_n_battle.png")
-	# description 
-	I_N_CONFIRM = RuleImage(roi_front=(670,402,176,63), roi_back=(670,402,176,63), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/0110/0110_n_confirm.png")
-	# description 
-	I_C_CONFIRM1 = RuleImage(roi_front=(560,341,37,38), roi_back=(560,341,37,38), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/0110/0110_c_confirm1.png")
-
-
-	# Click Rule Assets
-	# description 
-	C_RANDOM_LEFT = RuleClick(roi_front=(21,23,237,599), roi_back=(21,23,237,599), name="random_left")
-	# description 
-	C_RANDOM_RIGHT = RuleClick(roi_front=(1047,55,218,638), roi_back=(1047,55,218,638), name="random_right")
-	# description 
-	C_RANDOM_TOP = RuleClick(roi_front=(85,46,1159,101), roi_back=(85,46,1159,101), name="random_top")
-	# description 
-	C_RANDOM_BOTTOM = RuleClick(roi_front=(182,539,1063,100), roi_back=(182,539,1063,100), name="random_bottom")
+	C_RANDOM_BOTTOM = RuleClick(roi_front=(179,577,972,100), roi_back=(179,579,972,100), name="random_bottom")
 	# description 
 	# description 
 	C_RANDOM_ALL = RuleClick(roi_front=(42,94,1207,543), roi_back=(42,94,1207,543), name="random_all")
 	C_RANDOM_ALL = RuleClick(roi_front=(42,94,1207,543), roi_back=(42,94,1207,543), name="random_all")
-	# 替换buff1 
-	C_BUFF_1_UP = RuleClick(roi_front=(204,626,134,39), roi_back=(204,626,134,39), name="buff_1_up")
-	# 替换buff2 
-	C_BUFF_2_UP = RuleClick(roi_front=(414,625,134,39), roi_back=(414,625,134,39), name="buff_2_up")
-	# 替换buff3 
-	C_BUFF_3_UP = RuleClick(roi_front=(619,625,134,39), roi_back=(619,625,134,39), name="buff_3_up")
-	# 替换buff4 
-	C_BUFF_4_UP = RuleClick(roi_front=(831,625,134,39), roi_back=(831,625,134,39), name="buff_4_up")
-	# 替换buff5 
-	C_BUFF_5_UP = RuleClick(roi_front=(1043,624,134,39), roi_back=(1043,624,134,39), name="buff_5_up")
-	# 上阵buff_1位置 
-	C_BUFF_1_BOX = RuleClick(roi_front=(333,338,70,72), roi_back=(333,338,70,72), name="buff_1_box")
-	# 上阵buff_2位置 
-	C_BUFF_2_BOX = RuleClick(roi_front=(877,220,59,62), roi_back=(877,220,59,62), name="buff_2_box")
 
 
 
 
 	# Image Rule Assets
 	# Image Rule Assets
-	# 进入活动 
-	I_SHI = RuleImage(roi_front=(1183,319,47,38), roi_back=(1164,134,83,318), threshold=0.7, method="Template matching", file="./tasks/ActivityShikigami/as/as_shi.png")
-	# 左上角返回 
-	I_BACK_GREEN = RuleImage(roi_front=(27,19,34,38), roi_back=(2,1,170,75), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_back_green.png")
-	# 征伐斗场 
-	I_BATTLE = RuleImage(roi_front=(813,254,35,135), roi_back=(754,140,154,315), threshold=0.7, method="Template matching", file="./tasks/ActivityShikigami/as/as_battle.png")
-	# 进入爬塔1 
-	I_BATTLE_1 = RuleImage(roi_front=(541,197,149,26), roi_back=(506,622,273,96), threshold=0.7, method="Template matching", file="./tasks/ActivityShikigami/as/as_battle_1.png")
-	# 归鹿之途 
-	I_DRUM = RuleImage(roi_front=(327,627,145,28), roi_back=(256,462,301,232), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_drum.png")
 	# 上锁图标 
 	# 上锁图标 
-	I_LOCK = RuleImage(roi_front=(884,648,28,25), roi_back=(761,613,255,76), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_lock.png")
+	I_LOCK = RuleImage(roi_front=(825,657,28,25), roi_back=(739,613,276,85), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_lock.png")
 	# 还未上锁图片 
 	# 还未上锁图片 
-	I_UNLOCK = RuleImage(roi_front=(884,648,28,25), roi_back=(758,607,242,85), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_unlock.png")
+	I_UNLOCK = RuleImage(roi_front=(884,648,28,25), roi_back=(733,607,266,95), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_unlock.png")
 	# 寿司体力 
 	# 寿司体力 
 	I_AP = RuleImage(roi_front=(1181,657,23,24), roi_back=(1149,631,103,71), threshold=0.65, method="Template matching", file="./tasks/ActivityShikigami/as/as_ap.png")
 	I_AP = RuleImage(roi_front=(1181,657,23,24), roi_back=(1149,631,103,71), threshold=0.65, method="Template matching", file="./tasks/ActivityShikigami/as/as_ap.png")
 	# 活动体力 
 	# 活动体力 
@@ -82,58 +38,76 @@ class ActivityShikigamiAssets:
 	I_BUY_JADE = RuleImage(roi_front=(1004,192,38,42), roi_back=(836,619,38,42), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buy_jade.png")
 	I_BUY_JADE = RuleImage(roi_front=(1004,192,38,42), roi_back=(836,619,38,42), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buy_jade.png")
 	# 增加到最大 
 	# 增加到最大 
 	I_ADD_MAX = RuleImage(roi_front=(17,24,33,37), roi_back=(974,524,57,54), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_add_max.png")
 	I_ADD_MAX = RuleImage(roi_front=(17,24,33,37), roi_back=(974,524,57,54), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_add_max.png")
+	# description 
+	I_TOGGLE_BUTTON = RuleImage(roi_front=(1193,463,27,25), roi_back=(1169,146,73,403), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_toggle_button.png")
+
+
+	# Image Rule Assets
+	# 进入活动 
+	I_SHI = RuleImage(roi_front=(1182,391,47,29), roi_back=(1164,134,83,318), threshold=0.7, method="Template matching", file="./tasks/ActivityShikigami/as/as_shi.png")
+	# 左上角返回 
+	I_BACK_GREEN = RuleImage(roi_front=(27,19,34,38), roi_back=(2,1,170,75), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_back_green.png")
 	# 右上跳过按钮 
 	# 右上跳过按钮 
 	I_SKIP_BUTTON = RuleImage(roi_front=(1159,37,51,22), roi_back=(1141,27,86,43), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_skip_button.png")
 	I_SKIP_BUTTON = RuleImage(roi_front=(1159,37,51,22), roi_back=(1141,27,86,43), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_skip_button.png")
 	# 红色退出 
 	# 红色退出 
 	I_RED_EXIT = RuleImage(roi_front=(1162,96,39,38), roi_back=(1120,49,110,135), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_red_exit.png")
 	I_RED_EXIT = RuleImage(roi_front=(1162,96,39,38), roi_back=(1120,49,110,135), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_red_exit.png")
+	# 进入主要的战斗界面 
+	I_TO_BATTLE_MAIN = RuleImage(roi_front=(646,121,39,176), roi_back=(606,91,100,241), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_to_battle_main.png")
+	# 点击进入boss战斗页面 
+	I_TO_BATTLE_BOSS = RuleImage(roi_front=(931,217,37,173), roi_back=(909,198,100,219), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_to_battle_boss.png")
 	# description 
 	# description 
-	I_TOGGLE_BUTTON = RuleImage(roi_front=(1193,463,27,25), roi_back=(1169,146,73,403), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_toggle_button.png")
-	# 爬塔进入首领战 
-	I_BOSS = RuleImage(roi_front=(165,339,33,132), roi_back=(103,218,160,355), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_boss.png")
-	# 爬塔boss战页面检查图像 
-	I_CHECK_BOSS = RuleImage(roi_front=(87,18,126,37), roi_back=(63,0,172,81), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_boss.png")
-	# 爬塔活动副页检查标志 
-	I_CHECK_BATTLE_2 = RuleImage(roi_front=(22,632,61,69), roi_back=(1,601,109,117), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_battle_2.png")
-	# 爬塔活动页面的红色退出 
-	I_RED_EXIT_2 = RuleImage(roi_front=(1097,177,46,45), roi_back=(931,128,237,164), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_red_exit_2.png")
-	# 卸载buff 
-	I_BUFF_DOWN = RuleImage(roi_front=(428,625,100,37), roi_back=(177,600,1040,98), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buff_down.png")
-	# 切换buff按钮 
-	I_BUFF_CHANGE_BUTTON = RuleImage(roi_front=(491,604,48,46), roi_back=(439,574,197,108), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buff_change_button.png")
-	# buff容器1为空 
-	I_BUFF_BOX_1_EMPTY = RuleImage(roi_front=(342,345,50,59), roi_back=(317,322,100,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buff_box_1_empty.png")
-	# buff容器2为空 
-	I_BUFF_BOX_2_EMPTY = RuleImage(roi_front=(883,224,49,54), roi_back=(854,195,107,105), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buff_box_2_empty.png")
-	# 装配buff 
-	I_BUFF_UP = RuleImage(roi_front=(419,624,120,41), roi_back=(176,576,1025,142), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buff_up.png")
-	# buff切换 
-	I_BUFF_SWITCH = RuleImage(roi_front=(640,624,100,39), roi_back=(180,601,1026,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_buff_switch.png")
-	# 爬塔活动buff页 
-	I_CHECK_BUFF = RuleImage(roi_front=(91,12,130,47), roi_back=(77,0,156,83), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_buff.png")
-	# 进入门票活动 
-	I_ENTRY_ACTIVITY = RuleImage(roi_front=(567,258,46,42), roi_back=(254,56,774,524), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_entry_activity.png")
-	# 活动列表页爬塔活动 
-	I_CHECK_ACT_LIST_CLIMB_ACT = RuleImage(roi_front=(538,194,497,193), roi_back=(415,67,773,390), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_act_list_climb_act.png")
-	# 活动地图切换 
-	I_ACT_MAP_SWITCH = RuleImage(roi_front=(1196,303,59,48), roi_back=(1174,263,104,118), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_act_map_switch.png")
-	# 门票活动定位 
-	I_PASS_ACT_LOCAT = RuleImage(roi_front=(1214,395,29,31), roi_back=(1179,373,100,86), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_pass_act_locat.png")
+	I_CHECK_BATTLE_MAIN = RuleImage(roi_front=(30,130,75,46), roi_back=(17,104,100,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_battle_main.png")
+	# description 
+	I_CHECK_BATTLE_BOSS = RuleImage(roi_front=(0,0,100,100), roi_back=(0,0,100,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_battle_boss.png")
+	# 从main进入到式神录 
+	I_BATTLE_MAIN_TO_RECORDS = RuleImage(roi_front=(1208,112,39,42), roi_back=(1171,86,100,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_battle_main_to_records.png")
+
+
+	# Image Rule Assets
+	# description 
+	I_PASS_1 = RuleImage(roi_front=(359,295,100,53), roi_back=(68,203,1138,369), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_1.png")
+	# description 
+	I_PASS_2 = RuleImage(roi_front=(645,224,92,57), roi_back=(98,205,1076,366), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_2.png")
+	# description 
+	I_PASS_3 = RuleImage(roi_front=(648,227,91,55), roi_back=(103,162,1077,416), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_3.png")
+	# description 
+	I_PASS_4 = RuleImage(roi_front=(586,424,100,58), roi_back=(99,194,1080,398), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_4.png")
+	# 箱子 
+	I_PASS_5 = RuleImage(roi_front=(946,415,65,48), roi_back=(97,194,1036,398), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_5.png")
+	# 印记 
+	I_PASS_6 = RuleImage(roi_front=(668,221,54,50), roi_back=(107,159,1012,394), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_6.png")
+	# description 
+	I_PASS_7 = RuleImage(roi_front=(329,233,51,51), roi_back=(95,180,1056,394), threshold=0.65, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_7.png")
+	# 印记选中间的 
+	I_PASS_8 = RuleImage(roi_front=(579,276,100,100), roi_back=(577,296,100,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_8.png")
+	# description 
+	I_PASS_9 = RuleImage(roi_front=(558,643,160,44), roi_back=(480,601,306,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_9.png")
+	# 印记选左边的 
+	I_PASS_10 = RuleImage(roi_front=(279,309,100,100), roi_back=(291,305,100,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_10.png")
+	# 印记选右边的 
+	I_PASS_11 = RuleImage(roi_front=(918,304,100,100), roi_back=(914,308,100,100), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_11.png")
+	# 击败魇兽将直接前往下一层 
+	I_PASS12 = RuleImage(roi_front=(870,356,100,50), roi_back=(104,169,1109,425), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass12.png")
+	# 魇兽将的战斗图片 
+	I_PASS_13 = RuleImage(roi_front=(1018,570,100,100), roi_back=(984,538,169,152), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/fire/fire_pass_13.png")
 
 
 
 
 	# Ocr Rule Assets
 	# Ocr Rule Assets
+	# 挑战 
+	O_FIRE = RuleOcr(roi=(1137,599,83,44), area=(1129,570,100,100), mode="Single", method="Default", keyword="挑战", name="fire")
 	# 体力的数量检测 
 	# 体力的数量检测 
-	O_REMAIN_AP = RuleOcr(roi=(727,18,105,28), area=(716,11,122,41), mode="DigitCounter", method="Default", keyword="", name="remain_ap")
+	O_REMAIN_AP = RuleOcr(roi=(749,18,73,29), area=(749,18,73,29), mode="DigitCounter", method="Default", keyword="", name="remain_ap")
 	# 活动体力的剩余检测 
 	# 活动体力的剩余检测 
-	O_REMAIN_AP_ACTIVITY = RuleOcr(roi=(534,18,70,28), area=(534,18,70,28), mode="DigitCounter", method="Default", keyword="", name="remain_ap_activity")
+	O_REMAIN_PASS = RuleOcr(roi=(959,18,57,28), area=(959,18,57,28), mode="DigitCounter", method="Default", keyword="", name="remain_pass")
 	# 还有多少次购买体力的机会 
 	# 还有多少次购买体力的机会 
 	O_REMAIN_BUY = RuleOcr(roi=(808,531,39,42), area=(808,531,39,42), mode="DigitCounter", method="Default", keyword="", name="remain_buy")
 	O_REMAIN_BUY = RuleOcr(roi=(808,531,39,42), area=(808,531,39,42), mode="DigitCounter", method="Default", keyword="", name="remain_buy")
 	# 活动票数(没有百分比) 
 	# 活动票数(没有百分比) 
-	O_REMAIN_AP_ACTIVITY2 = RuleOcr(roi=(1115,25,88,29), area=(1107,14,103,50), mode="Digit", method="Default", keyword="", name="remain_ap_activity2")
-	# 从左侧进入战斗 
-	O_ENTRY_ACTIVITY = RuleOcr(roi=(72,279,98,32), area=(73,279,98,32), mode="Single", method="Default", keyword="临战演武", name="entry_activity")
+	O_REMAIN_PASS2 = RuleOcr(roi=(1115,25,88,29), area=(1107,14,103,50), mode="Digit", method="Default", keyword="", name="remain_pass2")
 	# boss剩余攻击次数 
 	# boss剩余攻击次数 
 	O_REMAIN_BOSS = RuleOcr(roi=(1113,669,131,31), area=(1099,659,162,52), mode="DigitCounter", method="Default", keyword="", name="remain_boss")
 	O_REMAIN_BOSS = RuleOcr(roi=(1113,669,131,31), area=(1099,659,162,52), mode="DigitCounter", method="Default", keyword="", name="remain_boss")
-	# 挑战 
-	O_FIRE = RuleOcr(roi=(1137,599,83,44), area=(1129,570,100,100), mode="Single", method="Default", keyword="挑战", name="fire")
+	# 100体活动门票检测 
+	O_REMAIN_AP100 = RuleOcr(roi=(922,21,112,39), area=(913,8,131,62), mode="Digit", method="Default", keyword="", name="remain_ap100")
+	# 进入100体活动标识 
+	O_ENTER_AP100 = RuleOcr(roi=(73,98,95,32), area=(5,79,256,108), mode="Single", method="Default", keyword="将魂试炼", name="enter_ap100")
 
 
 
 

+ 72 - 29
tasks/ActivityShikigami/config.py

@@ -1,9 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
-from enum import Enum
-from datetime import time, timedelta
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
 
 
 from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType
 from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_scheduler import Scheduler
@@ -11,62 +9,107 @@ from tasks.Component.config_base import ConfigBase, TimeDelta
 from tasks.Component.BaseActivity.config_activity import GeneralClimb
 from tasks.Component.BaseActivity.config_activity import GeneralClimb
 
 
 
 
-class ShikigamiType(str, Enum):
-    FOOD_TYPE_1 = 'shikigami_type_1'
-    FOOD_TYPE_2 = 'shikigami_type_2'
-    FOOD_TYPE_3 = 'shikigami_type_3'
-    FOOD_TYPE_4 = 'shikigami_type_4'
+def check_soul_by_number(enable_switch: bool, group_team: str, label: str):
+    if not enable_switch:
+        return
+    if not group_team or group_team == "-1,-1":
+        raise ValueError(f"[{label}]Switch Soul configuration is enabled, but there is no setting")
+    if ',' not in group_team:
+        raise ValueError(f"[{label}]The switch soul configuration must be in English ','")
+    parts = group_team.split(',')
+    if len(parts) != 2:
+        raise ValueError(f"[{label}]The length of the switch soul configuration must be equal to 2")
+    if not all(p.strip().isdigit() for p in parts):
+        raise ValueError(f"[{label}]Switching soul configurations must be numeric")
+
+
+def check_soul_by_ocr(enable_switch: bool, group_team: str, label: str):
+    if not enable_switch:
+        return
+    if not group_team:
+        raise ValueError(f"[{label}]Switch Soul configuration is enabled, but there is no setting")
+    if ',' not in group_team:
+        raise ValueError(f"[{label}]The switch soul configuration must be in English ','")
+    parts = group_team.split(',')
+    if len(parts) != 2:
+        raise ValueError(f"[{label}]The length of the switch soul configuration must be equal to 2")
 
 
 
 
 class SwitchSoulConfig(BaseModel):
 class SwitchSoulConfig(BaseModel):
-    # 切换门票爬塔御魂
     enable_switch_pass: bool = Field(default=False, description='是否切换门票爬塔御魂')
     enable_switch_pass: bool = Field(default=False, description='是否切换门票爬塔御魂')
-    pass_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔。战斗内切换队伍预设也使用该值')
+    pass_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
     enable_switch_pass_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     enable_switch_pass_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     pass_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
     pass_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
-    # 切换体力爬塔御魂
+
     enable_switch_ap: bool = Field(default=False, description='是否切换体力爬塔御魂')
     enable_switch_ap: bool = Field(default=False, description='是否切换体力爬塔御魂')
-    ap_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔。战斗内切换队伍预设也使用该值')
+    ap_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
     enable_switch_ap_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     enable_switch_ap_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     ap_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
     ap_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
-    # 切换boss爬塔御魂
+
     enable_switch_boss: bool = Field(default=False, description='是否切换boss爬塔御魂')
     enable_switch_boss: bool = Field(default=False, description='是否切换boss爬塔御魂')
-    boss_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔。战斗内切换队伍预设也使用该值')
+    boss_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
     enable_switch_boss_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     enable_switch_boss_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     boss_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
     boss_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
 
 
+    enable_switch_ap100: bool = Field(default=False, description='是否切换100体爬塔御魂')
+    ap100_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
+    enable_switch_ap100_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
+    ap100_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
+
+    # @model_validator(mode='after')
+    def validate_switch_soul(self):
+        label_set = self.get_label_set()
+        for label in label_set:
+            enable_num = getattr(self, f"enable_switch_{label}", False)
+            team = getattr(self, f"{label}_group_team", None)
+            check_soul_by_number(enable_num, team, label=label.upper())
+
+            enable_ocr = getattr(self, f"enable_switch_{label}_by_name", False)
+            team_name = getattr(self, f"{label}_group_team_name", None)
+            check_soul_by_ocr(enable_ocr, team_name, label=label.upper())
+        return self
+
+    def get_label_set(self):
+        return {field.replace("enable_switch_", "") for field in self.model_fields if
+                     field.startswith("enable_switch_") and not field.endswith("by_name")}
+
 
 
 class GeneralBattleConfig(BaseModel):
 class GeneralBattleConfig(BaseModel):
-    # 是否切换门票爬塔预设
-    enable_pass_preset: bool = Field(default=False, description='是否切换门票爬塔预设')
-    # 是否开启门票爬塔绿标
+    enable_pass_preset: bool = Field(default=False, description='是否切换门票爬塔预设, 仅数字切换御魂可用')
     enable_pass_green: bool = Field(default=False, description='是否开启门票爬塔绿标')
     enable_pass_green: bool = Field(default=False, description='是否开启门票爬塔绿标')
-    # 门票爬塔绿标位置
     pass_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='门票爬塔绿标位置')
     pass_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='门票爬塔绿标位置')
-    # 门票爬塔战斗过程是否随机点击或滑动
     enable_pass_anti_detect: bool = Field(default=False, description='门票爬塔战斗过程是否随机点击或滑动')
     enable_pass_anti_detect: bool = Field(default=False, description='门票爬塔战斗过程是否随机点击或滑动')
 
 
-    # 是否切换体力爬塔预设
-    enable_ap_preset: bool = Field(default=False, description='是否切换体力爬塔预设')
-    # 是否开启体力爬塔绿标
+    enable_ap_preset: bool = Field(default=False, description='是否切换体力爬塔预设, 仅数字切换御魂可用')
     enable_ap_green: bool = Field(default=False, description='是否开启体力爬塔绿标')
     enable_ap_green: bool = Field(default=False, description='是否开启体力爬塔绿标')
-    # 体力爬塔绿标位置
     ap_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='体力爬塔绿标位置')
     ap_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='体力爬塔绿标位置')
-    # 体力爬塔战斗过程是否随机点击或滑动
     enable_ap_anti_detect: bool = Field(default=False, description='体力爬塔战斗过程是否随机点击或滑动')
     enable_ap_anti_detect: bool = Field(default=False, description='体力爬塔战斗过程是否随机点击或滑动')
 
 
-    # 是否切换boss爬塔预设
-    enable_boss_preset: bool = Field(default=False, description='是否切换boss爬塔预设')
-    # 是否开启boss爬塔绿标
+    enable_boss_preset: bool = Field(default=False, description='是否切换boss爬塔预设, 仅数字切换御魂可用')
     enable_boss_green: bool = Field(default=False, description='是否开启boss爬塔绿标')
     enable_boss_green: bool = Field(default=False, description='是否开启boss爬塔绿标')
-    # boss爬塔绿标位置
     boss_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='boss爬塔绿标位置')
     boss_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='boss爬塔绿标位置')
-    # boss爬塔战斗过程是否随机点击或滑动
     enable_boss_anti_detect: bool = Field(default=False, description='boss爬塔战斗过程是否随机点击或滑动')
     enable_boss_anti_detect: bool = Field(default=False, description='boss爬塔战斗过程是否随机点击或滑动')
 
 
+    enable_ap100_preset: bool = Field(default=False, description='是否切换100体爬塔预设, 仅数字切换御魂可用')
+    enable_ap100_green: bool = Field(default=False, description='是否开启100体爬塔绿标')
+    ap100_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='100体爬塔绿标位置')
+    enable_ap100_anti_detect: bool = Field(default=False, description='100体爬塔战斗过程是否随机点击或滑动')
+
 
 
 class ActivityShikigami(ConfigBase):
 class ActivityShikigami(ConfigBase):
     scheduler: Scheduler = Field(default_factory=Scheduler)
     scheduler: Scheduler = Field(default_factory=Scheduler)
     general_climb: GeneralClimb = Field(default_factory=GeneralClimb)
     general_climb: GeneralClimb = Field(default_factory=GeneralClimb)
     switch_soul_config: SwitchSoulConfig = Field(default_factory=SwitchSoulConfig)
     switch_soul_config: SwitchSoulConfig = Field(default_factory=SwitchSoulConfig)
     general_battle: GeneralBattleConfig = Field(default_factory=GeneralBattleConfig)
     general_battle: GeneralBattleConfig = Field(default_factory=GeneralBattleConfig)
+
+    # @model_validator(mode='after')
+    def validate_switch_preset(self):
+        label_set = self.switch_soul_config.get_label_set()
+        for label in label_set:
+            enable_preset = getattr(self.general_battle, f"enable_{label}_preset", False)
+            group_team = getattr(self.switch_soul_config, f"{label}_group_team", None)
+            try:
+                check_soul_by_number(enable_preset, group_team, label=label.upper())
+            except ValueError:
+                raise ValueError(f'The switch preset is enabled, but the switch soul is configured incorrectly')
+        return self

BIN
tasks/ActivityShikigami/fire/fire_pass12.png


BIN
tasks/ActivityShikigami/fire/fire_pass_1.png


BIN
tasks/ActivityShikigami/fire/fire_pass_13.png


BIN
tasks/ActivityShikigami/fire/fire_pass_2.png


BIN
tasks/ActivityShikigami/fire/fire_pass_3.png


BIN
tasks/ActivityShikigami/fire/fire_pass_4.png


BIN
tasks/ActivityShikigami/fire/fire_pass_5.png


BIN
tasks/ActivityShikigami/fire/fire_pass_6.png


BIN
tasks/ActivityShikigami/fire/fire_pass_7.png


BIN
tasks/ActivityShikigami/fire/fire_pass_9.png


+ 119 - 0
tasks/ActivityShikigami/fire/image.json

@@ -0,0 +1,119 @@
+[
+  {
+    "itemName": "pass_1",
+    "imageName": "fire_pass_1.png",
+    "roiFront": "359,295,100,53",
+    "roiBack": "68,203,1138,369",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "pass_2",
+    "imageName": "fire_pass_2.png",
+    "roiFront": "645,224,92,57",
+    "roiBack": "98,205,1076,366",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "pass_3",
+    "imageName": "fire_pass_3.png",
+    "roiFront": "648,227,91,55",
+    "roiBack": "103,162,1077,416",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "pass_4",
+    "imageName": "fire_pass_4.png",
+    "roiFront": "586,424,100,58",
+    "roiBack": "99,194,1080,398",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "pass_5",
+    "imageName": "fire_pass_5.png",
+    "roiFront": "946,415,65,48",
+    "roiBack": "97,194,1036,398",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "箱子"
+  },
+  {
+    "itemName": "pass_6",
+    "imageName": "fire_pass_6.png",
+    "roiFront": "668,221,54,50",
+    "roiBack": "107,159,1012,394",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "印记"
+  },
+  {
+    "itemName": "pass_7",
+    "imageName": "fire_pass_7.png",
+    "roiFront": "329,233,51,51",
+    "roiBack": "95,180,1056,394",
+    "method": "Template matching",
+    "threshold": 0.65,
+    "description": "description"
+  },
+  {
+    "itemName": "pass_8",
+    "imageName": "fire_pass_8.png",
+    "roiFront": "579,276,100,100",
+    "roiBack": "577,296,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "印记选中间的"
+  },
+  {
+    "itemName": "pass_9",
+    "imageName": "fire_pass_9.png",
+    "roiFront": "558,643,160,44",
+    "roiBack": "480,601,306,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "pass_10",
+    "imageName": "fire_pass_10.png",
+    "roiFront": "279,309,100,100",
+    "roiBack": "291,305,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "印记选左边的"
+  },
+  {
+    "itemName": "pass_11",
+    "imageName": "fire_pass_11.png",
+    "roiFront": "918,304,100,100",
+    "roiBack": "914,308,100,100",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "印记选右边的"
+  },
+  {
+    "itemName": "pass12",
+    "imageName": "fire_pass12.png",
+    "roiFront": "870,356,100,50",
+    "roiBack": "104,169,1109,425",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "击败魇兽将直接前往下一层"
+  },
+  {
+    "itemName": "pass_13",
+    "imageName": "fire_pass_13.png",
+    "roiFront": "1018,570,100,100",
+    "roiBack": "984,538,169,152",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "魇兽将的战斗图片"
+  }
+]

+ 30 - 20
tasks/ActivityShikigami/as/ocr.json → tasks/ActivityShikigami/fire/ocr.json

@@ -1,17 +1,26 @@
 [
 [
+  {
+    "itemName": "fire",
+    "roiFront": "1137,599,83,44",
+    "roiBack": "1129,570,100,100",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "挑战",
+    "description": "挑战"
+  },
   {
   {
     "itemName": "remain_ap",
     "itemName": "remain_ap",
-    "roiFront": "727,18,105,28",
-    "roiBack": "716,11,122,41",
+    "roiFront": "749,18,73,29",
+    "roiBack": "749,18,73,29",
     "mode": "DigitCounter",
     "mode": "DigitCounter",
     "method": "Default",
     "method": "Default",
     "keyword": "",
     "keyword": "",
     "description": "体力的数量检测"
     "description": "体力的数量检测"
   },
   },
   {
   {
-    "itemName": "remain_ap_activity",
-    "roiFront": "534,18,70,28",
-    "roiBack": "534,18,70,28",
+    "itemName": "remain_pass",
+    "roiFront": "959,18,57,28",
+    "roiBack": "959,18,57,28",
     "mode": "DigitCounter",
     "mode": "DigitCounter",
     "method": "Default",
     "method": "Default",
     "keyword": "",
     "keyword": "",
@@ -27,7 +36,7 @@
     "description": "还有多少次购买体力的机会"
     "description": "还有多少次购买体力的机会"
   },
   },
   {
   {
-    "itemName": "remain_ap_activity2",
+    "itemName": "remain_pass2",
     "roiFront": "1115,25,88,29",
     "roiFront": "1115,25,88,29",
     "roiBack": "1107,14,103,50",
     "roiBack": "1107,14,103,50",
     "mode": "Digit",
     "mode": "Digit",
@@ -35,15 +44,6 @@
     "keyword": "",
     "keyword": "",
     "description": "活动票数(没有百分比)"
     "description": "活动票数(没有百分比)"
   },
   },
-  {
-    "itemName": "entry_activity",
-    "roiFront": "72,279,98,32",
-    "roiBack": "73,279,98,32",
-    "mode": "Single",
-    "method": "Default",
-    "keyword": "临战演武",
-    "description": "从左侧进入战斗"
-  },
   {
   {
     "itemName": "remain_boss",
     "itemName": "remain_boss",
     "roiFront": "1113,669,131,31",
     "roiFront": "1113,669,131,31",
@@ -53,13 +53,23 @@
     "keyword": "",
     "keyword": "",
     "description": "boss剩余攻击次数"
     "description": "boss剩余攻击次数"
   },
   },
+
+    {
+    "itemName": "remain_ap100",
+    "roiFront": "922,21,112,39",
+    "roiBack": "913,8,131,62",
+    "mode": "Digit",
+    "method": "Default",
+    "keyword": "",
+    "description": "100体活动门票检测"
+  },
   {
   {
-    "itemName": "fire",
-    "roiFront": "1137,599,83,44",
-    "roiBack": "1129,570,100,100",
+    "itemName": "enter_ap100",
+    "roiFront": "73,98,95,32",
+    "roiBack": "5,79,256,108",
     "mode": "Single",
     "mode": "Single",
     "method": "Default",
     "method": "Default",
-    "keyword": "挑战",
-    "description": "挑战"
+    "keyword": "将魂试炼",
+    "description": "进入100体活动标识"
   }
   }
 ]
 ]

+ 68 - 0
tasks/ActivityShikigami/page.py

@@ -0,0 +1,68 @@
+from tasks.ActivityShikigami.assets import ActivityShikigamiAssets as asa
+from tasks.GameUi.page import Page, page_main
+from tasks.GlobalGame.assets import GlobalGameAssets as gga
+from tasks.GameUi.assets import GameUiAssets as G
+from tasks.Component.RightActivity.assets import RightActivityAssets as RAA
+from tasks.base_task import BaseTask as BT
+
+# ************************************* 活动部分 *****************************************#
+
+# 活动列表页 act_list
+# page_act_list = Page(G.I_CHECK_ACT_LIST)
+# page_act_list.additional = [G.I_PAPER_DOLL_CLOSE]
+# page_act_list.link(button=G.I_BACK_ACT_LIST, destination=page_main)
+# page_main.link(button=G.I_ACT_LIST_EXPAND, destination=page_act_list)
+# # 活动列表页爬塔活动
+# page_act_list_climb_act = Page(asa.I_CHECK_ACT_LIST_CLIMB_ACT)
+# page_act_list.link(button=G.L_ACT_LIST_OCR, destination=page_act_list_climb_act)
+# page_act_list_climb_act.link(button=G.I_BACK_ACT_LIST, destination=page_main)
+
+# 爬塔活动主要界面
+page_climb_act = Page(asa.I_TO_BATTLE_MAIN)
+page_climb_act.additional = [gga.I_UI_REWARD, asa.I_SKIP_BUTTON, asa.I_RED_EXIT]
+page_climb_act.link(button=G.I_BACK_Y, destination=page_main)
+page_main.link(button=[asa.I_SHI, RAA.I_TOGGLE_BUTTON], destination=page_climb_act)
+
+# page_act_list_climb_act.link(button=G.I_ACT_LIST_GOTO_ACT, destination=page_climb_act)
+# # 爬塔活动副界面
+# page_climb_act_2 = Page(asa.I_CHECK_BATTLE_2)
+# page_climb_act_2.additional = [asa.I_ACT_MAP_SWITCH, asa.I_PASS_ACT_LOCAT, asa.I_SKIP_BUTTON, asa.I_RED_EXIT,
+#                                asa.I_RED_EXIT_2]
+# page_climb_act_2.link(button=G.I_BACK_BATTLE, destination=page_climb_act)
+# page_climb_act.link(button=asa.I_BATTLE, destination=page_climb_act_2)
+# # 门票爬塔活动界面
+# page_climb_act_pass = Page(asa.I_AP_ACTIVITY)
+# page_climb_act_pass.additional = [asa.I_SKIP_BUTTON, gga.I_UI_REWARD, asa.I_RED_EXIT, ]
+# page_climb_act_pass.link(button=G.I_BACK_Y, destination=page_climb_act_2)
+# page_climb_act_2.link(button=asa.I_ENTRY_ACTIVITY, destination=page_climb_act_pass)
+# # 体力爬塔活动界面
+# page_climb_act_ap = Page(asa.I_AP)
+# page_climb_act_ap.additional = [asa.O_ENTRY_ACTIVITY, asa.I_SKIP_BUTTON, asa.I_TOGGLE_BUTTON, gga.I_UI_REWARD,
+#                                 asa.I_RED_EXIT]
+# page_climb_act_ap.link(button=G.I_BACK_Y, destination=page_climb_act_2)
+# page_climb_act_2.link(button=asa.O_ENTRY_ACTIVITY, destination=page_climb_act_ap)
+# # 体力, 门票互相跳转
+# # page_climb_act_ap.link(button=asa.I_SWITCH, destination=page_climb_act_pass)
+# # page_climb_act_pass.link(button=asa.I_SWITCH, destination=page_climb_act_ap)
+# # 100体爬塔活动界面
+# page_climb_act_ap100 = Page(asa.I_CHECK_AP100)
+# page_climb_act_2.link(button=asa.O_ENTER_AP100, destination=page_climb_act_ap100)
+# page_climb_act_ap100.link(button=G.I_BACK_Y, destination=page_climb_act_2)
+# # 爬塔活动boss战界面
+# page_climb_act_boss = Page(asa.I_CHECK_BOSS)
+# page_climb_act_boss.additional = [BT.I_UI_BACK_RED, asa.I_SKIP_BUTTON]
+# page_climb_act_boss.link(button=G.I_BACK_Y, destination=page_climb_act)
+# page_climb_act.link(button=asa.I_BOSS, destination=page_climb_act_boss)
+# # 爬塔活动加成界面
+# page_climb_act_buff = Page(asa.I_CHECK_BUFF)
+# page_climb_act_buff.additional = [BT.I_UI_BACK_RED, asa.I_SKIP_BUTTON]
+# page_climb_act_buff.link(button=G.I_BACK_Y, destination=page_climb_act)
+# page_climb_act.link(button=asa.I_BUFF_CHANGE_BUTTON, destination=page_climb_act_buff)
+#
+# page_reward.link(button=random_click(), destination=page_climb_act_pass)
+# page_reward.link(button=random_click(), destination=page_climb_act_ap)
+# page_reward.link(button=random_click(), destination=page_climb_act_boss)
+#
+# page_failed.link(button=random_click(), destination=page_climb_act_pass)
+# page_failed.link(button=random_click(), destination=page_climb_act_ap)
+# page_failed.link(button=random_click(), destination=page_climb_act_boss)

+ 290 - 300
tasks/ActivityShikigami/script_task.py

@@ -3,32 +3,31 @@
 # github https://github.com/runhey
 # github https://github.com/runhey
 from enum import Enum, auto
 from enum import Enum, auto
 from time import sleep
 from time import sleep
-
+from datetime import datetime, timedelta
 import cv2
 import cv2
 import numpy as np
 import numpy as np
 import random
 import random
-import tasks.Component.GeneralBattle.config_general_battle
-from datetime import datetime, timedelta, time
+from typing import Any
+from cached_property import cached_property
+
+from module.atom.image import RuleImage
 from module.atom.click import RuleClick
 from module.atom.click import RuleClick
 from module.atom.ocr import RuleOcr
 from module.atom.ocr import RuleOcr
 from module.base.protect import random_sleep
 from module.base.protect import random_sleep
+from module.base.timer import Timer
 from module.exception import TaskEnd
 from module.exception import TaskEnd
 from module.logger import logger
 from module.logger import logger
+
+from tasks.base_task import BaseTask
+from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
 from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
 from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
-from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig
+from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig, ActivityShikigami
 from tasks.Component.BaseActivity.base_activity import BaseActivity
 from tasks.Component.BaseActivity.base_activity import BaseActivity
 from tasks.Component.BaseActivity.config_activity import GeneralClimb
 from tasks.Component.BaseActivity.config_activity import GeneralClimb
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.game_ui import GameUi
-import tasks.GameUi.page as game
-from typing import Any
-
-
-def get_run_order_list(climb_conf: GeneralClimb) -> list[str]:
-    if not climb_conf.run_sequence or len(climb_conf.run_sequence.split(',')) == 1:
-        raise ValueError('Run sequence now is empty, must set it')
-    run_order_list = [climb_type.strip() for climb_type in climb_conf.run_sequence.split(',')]
-    return [climb_type for climb_type in run_order_list if getattr(climb_conf, f'enable_{climb_type}', False)]
+import tasks.Component.GeneralBattle.config_general_battle
+import tasks.ActivityShikigami.page as game
 
 
 
 
 def _prepare_image_for_ocr(image: np.ndarray, asset: RuleOcr) -> np.ndarray:
 def _prepare_image_for_ocr(image: np.ndarray, asset: RuleOcr) -> np.ndarray:
@@ -75,382 +74,371 @@ def _prepare_image_for_ocr(image: np.ndarray, asset: RuleOcr) -> np.ndarray:
     return image_copy
     return image_copy
 
 
 
 
-class Status(Enum):
-    TIME_OUT = auto()  # 超时
-    DOWN = auto()  # 当前爬塔类型完成
-    ALL_DOWN = auto()  # 所有爬塔类型完成
-    ALREADY_SWITCH_SOUL = auto()  # 已经切换御魂
-    ALREADY_LOCK_TEAM = auto()  # 已经锁定队伍
-    ALREADY_SWITCH_BUFF = auto()  # 已经切换buff
-    GOTO_ACT_FAILED = auto()  # 前往活动失败
-    ENTER_BATTLE_FAILED = auto()  # 进入战斗失败
-
-
-class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
-    # key: climb type, value: run count
-    count_map: dict[str, int] = {
-        'pass': 0,
-        'ap': 0,
-        'boss': 0
-    }
-    page_map: dict[str, game.Page] = {
-        'pass': game.page_climb_act_pass,
-        'ap': game.page_climb_act_ap,
-        'boss': game.page_climb_act_boss,
-    }
-    # key: climb type, value: {status: value}
-    check_map: dict[str, dict[Status, Any]] = {}
-
-    climb_type: str = 'pass'
-    run_idx: int = 0
+class LimitTimeOut(Exception):
+    pass
 
 
+
+class LimitCountOut(Exception):
+    pass
+
+
+class StateMachine(BaseTask):
+    run_idx: int = 0  # 当前爬塔类型
+    _count_map = None
+
+    @cached_property
+    def conf(self) -> GeneralClimb:
+        return self.config.model.activity_shikigami
+
+    @property
+    def climb_type(self) -> str:
+        if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
+            return self.conf.general_climb.run_sequence_v[-1]
+        return self.conf.general_climb.run_sequence_v[self.run_idx]
+
+    @property
+    def count_map(self) -> dict[str, int]:
+        """
+        :return: key: climb type, value: run count
+        """
+        if not getattr(self, "_count_map", None):
+            self._count_map = {climb_type: 0 for climb_type in self.conf.general_climb.run_sequence_v}
+        return self._count_map
+
+    # ----------------------------------------------------
     def put_status(self):
     def put_status(self):
         """
         """
         更新全局状态
         更新全局状态
         """
         """
+
+        def get_count(self) -> int:
+            return self.count_map[self.climb_type]
+
+        def get_limit(self) -> int:
+            limit = getattr(self.conf.general_climb, f'{self.climb_type}_limit', 0)
+            return 0 if not limit else limit
+
         # 超过运行时间
         # 超过运行时间
         if self.limit_time is not None and datetime.now() - self.start_time >= self.limit_time:
         if self.limit_time is not None and datetime.now() - self.start_time >= self.limit_time:
-            logger.warning(f"Climb type {self.climb_type} time out")
-            self.put_check(Status.TIME_OUT, True)
+            logger.info(f"Climb type {self.climb_type} time out")
+            raise LimitTimeOut
         # 次数达到限制
         # 次数达到限制
-        if self.get_count() >= self.get_limit(self.config.activity_shikigami.general_climb):
+        if get_count(self) >= get_limit(self):
             logger.info(f"Climb type {self.climb_type} count limit reached")
             logger.info(f"Climb type {self.climb_type} count limit reached")
-            self.put_check(Status.DOWN, True)
+            raise LimitCountOut
+
+    def switch_next(self):
+        """
+        切换下一种爬塔类型
+        :return: True 切换成功 or False
+        """
+        self.run_idx += 1
+        if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
+            logger.info('All climbing activities have been completed')
+            return False
+        # 切换爬塔类型了, 恢复所有状态
+        self.current_count = 0
+        logger.hr(f'Climb switch to {self.climb_type}', 2)
+        return True
 
 
-    def check(self, status: Status) -> Any:
-        if len(self.check_map) == 0:
-            self.check_map = {climb_type: {state: None for state in list(Status)} for climb_type in
-                              get_run_order_list(self.config.activity_shikigami.general_climb)}
-        return self.check_map[self.climb_type][status]
 
 
-    def put_check(self, status: Status, value: Any):
-        self.check_map[self.climb_type][status] = value
+class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
+    """
+    更新前请先看 ./README.md
+    """
 
 
     def run(self) -> None:
     def run(self) -> None:
-        config = self.config.activity_shikigami
-        self.limit_time: timedelta = config.general_climb.limit_time
-        if isinstance(self.limit_time, time):
-            self.limit_time = timedelta(hours=self.limit_time.hour, minutes=self.limit_time.minute,
-                                        seconds=self.limit_time.second)
-        # 初始化爬塔类型
-        self.climb_type = get_run_order_list(config.general_climb)[0]
-        while True:
-            self.put_status()
-            # 超时或全部完成则退出
-            if self.check(Status.TIME_OUT) or self.check(Status.ALL_DOWN):
+        self.limit_time: timedelta = self.conf.general_climb.limit_time_v
+        #
+        for climb_type in self.conf.general_climb.run_sequence_v:
+            # 进入到活动的主页面,不是具体的战斗页面
+            self.ui_get_current_page()
+            self.ui_goto(game.page_climb_act)
+            try:
+                method_func = getattr(self, f'_run_{climb_type}')
+                method_func()
+            except LimitCountOut as e:
+                self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
+            except LimitTimeOut as e:
                 break
                 break
-            # 当前爬塔类型完成了, 切换下一个类型
-            if self.check(Status.DOWN):
+            finally:
+                # 切换下一个爬塔类型
                 self.switch_next()
                 self.switch_next()
-                continue
-            # 获取当前页面
-            current_page = self.ui_get_current_page(False)
-            # 检查是否已经切换御魂
-            if not self.check(Status.ALREADY_SWITCH_SOUL):
-                self.switch_soul(config.switch_soul_config)
-                continue
-            match current_page:
-                # 庭院, 进入活动主界面
-                case game.page_main:
-                    self.home_main()
-                # 活动主界面或副界面, 进入最终爬塔界面
-                case game.page_climb_act | game.page_climb_act_2:
-                    # self.ui_goto(game.page_climb_act_buff)
-                    self.goto_act()
-                # buff界面, 进入最终爬塔界面
-                case game.page_climb_act_buff:
-                    self.switch_buff(config.general_climb)
-                    self.goto_act()
-                # 最终爬塔界面
-                case game.page_climb_act_pass | game.page_climb_act_ap | game.page_climb_act_boss:
-                    if not self.check_can_run():
-                        continue
-                    self.lock_team(config.general_battle)
-                    self.start_battle()
-                case _:
-                    if self.check(Status.GOTO_ACT_FAILED):
-                        logger.warning(f'Climb type[{self.climb_type}] goto failed')
-                        self.put_check(Status.DOWN, True)
-                        continue
-                    self.put_check(Status.GOTO_ACT_FAILED, True)
-                    # 任何活动界面都没有识别到, 尝试主动前往爬塔活动
-                    self.goto_act()
+
         # 返回庭院
         # 返回庭院
-        self.main_home()
-        if config.general_climb.active_souls_clean:
+        logger.hr("Exit Shikigami", 2)
+        self.ui_get_current_page(False)
+        self.ui_goto(game.page_main)
+        if self.conf.general_climb.active_souls_clean:
             self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
             self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
         self.set_next_run(task="ActivityShikigami", success=True)
         self.set_next_run(task="ActivityShikigami", success=True)
         raise TaskEnd
         raise TaskEnd
 
 
+    def _run_pass(self):
+        """
+            更新前请先看 ./README.md
+        """
+        logger.hr(f'Start run climb type PASS', 1)
+        self.ui_click(self.I_TO_BATTLE_MAIN, stop=self.I_CHECK_BATTLE_MAIN, interval=1)
+        self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
+
+        ocr_limit_timer = Timer(1).start()
+        click_limit_timer = Timer(4).start()
+        while 1:
+            self.screenshot()
+            self.put_status()
+            # --------------------------------------------------------------
+            if (self.appear_then_click(self.I_UI_CONFIRM, interval=0.5)
+                    or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=0.5)):
+                continue
+            if self.ui_reward_appear_click():
+                continue
+            # 击败魇兽将直接前往下一层
+            # if self.appear(self.I_PASS12):
+            #     logger.info('Found魇兽将')
+            #     from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as GBC1
+            #     _battle_config = GBC1(lock_team_enable=True)
+            #     _battle_config.lock_team_enable = True
+            #     self.ui_click(self.I_PASS12, stop=self.I_PASS_13)
+            #     self.ui_click_until_disappear(self.I_PASS_13, interval=1)
+            #     self.run_general_battle(config=_battle_config)
+            #     continue
+            # 领箱子
+            if self.appear_then_click(self.I_PASS_5):
+                logger.info('Found箱子')
+                continue
+            # 印记
+            if self.appear(self.I_PASS_6):
+                logger.info('Found印记')
+                click_index = 0
+                clicks = [self.I_PASS_8, self.I_PASS_10, self.I_PASS_11]
+                self.ui_click(self.I_PASS_6, stop=self.I_UI_BACK_RED, interval=1)
+                self.screenshot()
+                if not self.appear(self.I_UI_BACK_RED):
+                    continue
+                while 1:
+                    self.screenshot()
+                    if self.ui_reward_appear_click():
+                        break
+                    if not self.appear(self.I_UI_BACK_RED):
+                        break
+                    # 按照顺序 间隔点击
+                    if self.click(clicks[click_index], interval=1):
+                        sleep(1.6)
+                        click_index += 1
+                        click_index = click_index % len(clicks)
+                    if self.appear_then_click(self.I_PASS_9, interval=1.1):
+                        logger.info('Select one done')
+                        continue
+            # 下一层
+            if self.appear_then_click(self.I_PASS_7, interval=1, threshold=0.65):
+                logger.info('Next layer')
+                continue
+            if click_limit_timer.reached():
+                click_limit_timer.reset()
+                if (self.appear_then_click(self.I_PASS_1)
+                        or self.appear_then_click(self.I_PASS_2)
+                        or self.appear_then_click(self.I_PASS_3)
+                        or self.appear_then_click(self.I_PASS_4)):
+                    continue
+            if not ocr_limit_timer.reached():
+                continue
+            ocr_limit_timer.reset()
+            if not self.ocr_appear(self.O_FIRE):
+                continue
+            #  --------------------------------------------------------------
+            self.lock_team(self.conf.general_battle)
+            if not self.check_tickets_enough():
+                logger.warning(f'No tickets left, wait for next time')
+                break
+            if self.conf.general_climb.random_sleep:
+                random_sleep(probability=0.2)
+            if self.start_battle():
+                continue
+
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
+
+    def _run_ap(self):
+        """
+            更新前请先看 ./README.md
+        """
+        logger.hr(f'Start run climb type AP')
+        self.ui_click(self.I_TO_BATTLE_MAIN, stop=self.I_CHECK_BATTLE_MAIN, interval=1)
+        self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
+
+        ocr_limit_timer = Timer(1).start()
+        while 1:
+            self.screenshot()
+            self.put_status()
+            # --------------------------------------------------------------
+            if not ocr_limit_timer.reached():
+                continue
+            ocr_limit_timer.reset()
+            if not self.ocr_appear(self.O_FIRE):
+                self.appear_then_click(self.I_CHECK_BATTLE_MAIN, interval=4)
+                continue
+            #  --------------------------------------------------------------
+            self.lock_team(self.conf.general_battle)
+            if not self.check_tickets_enough():
+                logger.warning(f'No tickets left, wait for next time')
+                break
+            if self.conf.general_climb.random_sleep:
+                random_sleep(probability=0.2)
+            if self.start_battle():
+                continue
+
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
+
+    def _run_boss(self):
+        """
+        更新前请先看 ./README.md
+        """
+        logger.hr(f'Start run climb type BOSS')
+
     def start_battle(self):
     def start_battle(self):
-        # 点击战斗前随机休息
-        if self.config.activity_shikigami.general_climb.random_sleep:
-            random_sleep(probability=0.2)
-        logger.info("Click battle")
-        click_times, max_times = 0, 3
+        click_times, max_times = 0, random.randint(2, 4)
         while 1:
         while 1:
             self.screenshot()
             self.screenshot()
             if self.is_in_battle(False):
             if self.is_in_battle(False):
                 break
                 break
             if click_times >= max_times:
             if click_times >= max_times:
-                if self.check(Status.ENTER_BATTLE_FAILED):
-                    logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
-                    self.put_check(Status.DOWN, True)
-                    return
-                logger.warning(f'Climb type {self.climb_type} enter fail, try reidentify')
-                self.put_check(Status.ENTER_BATTLE_FAILED, True)
+                logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
                 return
                 return
-            # 点击挑战
+            if (self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1) or
+                    self.appear_then_click(self.I_UI_CONFIRM, interval=1) ):
+                continue
             if self.ocr_appear_click(self.O_FIRE, interval=2):
             if self.ocr_appear_click(self.O_FIRE, interval=2):
                 click_times += 1
                 click_times += 1
-                continue
-            if self.appear_then_click(self.I_C_CONFIRM1, interval=0.6):
-                continue
-            if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
-                continue
-            if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
-                continue
-            if self.appear_then_click(self.I_N_CONFIRM, interval=1):
+                logger.info(f'Try click fire, remain times[{max_times - click_times}]')
                 continue
                 continue
         # 运行战斗
         # 运行战斗
-        if self.run_general_battle(config=self.get_general_battle_conf()):
-            self.count_map[self.climb_type] += 1
-            logger.info("General battle success")
+        self.run_general_battle(config=self.get_general_battle_conf())
 
 
     def battle_wait(self, random_click_swipt_enable: bool) -> bool:
     def battle_wait(self, random_click_swipt_enable: bool) -> bool:
         # 通用战斗结束判断
         # 通用战斗结束判断
         self.device.stuck_record_add("BATTLE_STATUS_S")
         self.device.stuck_record_add("BATTLE_STATUS_S")
         self.device.click_record_clear()
         self.device.click_record_clear()
-        logger.info("Start battle process")
-
+        logger.info(f"Start {self.climb_type} battle process")
+        self.count_map[self.climb_type] = self.current_count
         for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
         for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
             btn.name = "BATTLE_RANDOM"
             btn.name = "BATTLE_RANDOM"
         ok_cnt, max_retry = 0, 5
         ok_cnt, max_retry = 0, 5
+        single_start_time = datetime.now()
         while 1:
         while 1:
-            sleep(0.5)
+            sleep(random.uniform(0.5, 1.5))
             self.screenshot()
             self.screenshot()
-            # 已经回到对应挑战界面
-            if self.ui_page_appear(self.page_map[self.climb_type]):
-                break
-            # 达到最大重试次数且还没有识别到活动界面
+            # 达到最大重试次数则直接交给上层处理
             if ok_cnt > max_retry:
             if ok_cnt > max_retry:
-                # 跳出循环交由外部处理
                 break
                 break
-            # 失败
+            # 识别到挑战说明已经退出战斗
+            if ok_cnt > 0 and self.ocr_appear(self.O_FIRE):
+                return True
+            # 战斗失败
             if self.appear(self.I_FALSE):
             if self.appear(self.I_FALSE):
-                logger.warning("False battle")
+                logger.warning("Battle failed")
                 self.ui_click_until_smt_disappear(self.random_reward_click(click_now=False), self.I_FALSE, interval=1.5)
                 self.ui_click_until_smt_disappear(self.random_reward_click(click_now=False), self.I_FALSE, interval=1.5)
                 return False
                 return False
-            # 奖励界面
-            if self.ui_page_appear(game.page_reward):
-                logger.info(f'Battle end, try close {ok_cnt}')
-                self.random_reward_click(exclude_click=[self.C_RANDOM_BOTTOM])
-                ok_cnt += 1
-                continue
-            # 已经不在战斗中了, 且奖励也识别过了还不在活动界面, 则随机点击
-            if ok_cnt > 0 and not self.ui_page_appear(game.page_battle_auto):
-                self.random_reward_click(exclude_click=[self.C_RANDOM_BOTTOM])
-                ok_cnt += 1
+            # 战斗成功
+            if self.appear_then_click(self.I_WIN, interval=2):
                 continue
                 continue
+            #  出现 “魂” 和 紫蛇皮
+            if self.appear(self.I_REWARD):
+                logger.info('Win battle')
+                while 1:
+                    self.screenshot()
+                    appear_reward = self.appear_then_click(self.I_REWARD)
+                    appear_reward_purple_snake_skin = self.appear(self.I_REWARD_PURPLE_SNAKE_SKIN)
+                    if not appear_reward and not appear_reward_purple_snake_skin:
+                        break
+                    if appear_reward or appear_reward_purple_snake_skin:
+                        reward_click = random.choice(
+                            [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP])
+                        self.click(reward_click, interval=1.8)
+                        continue
+                return True
+            # 已经不在战斗中了, 且奖励也识别过了, 则随机点击
+            # if ok_cnt > 0 and not self.is_in_battle(False):
+            #     self.random_reward_click(exclude_click=[self.C_RANDOM_BOTTOM])
+            #     ok_cnt += 1
+            #     continue
+            # # 单局到时间自动退出战斗
+            # if ok_cnt == 0 and datetime.now() - single_start_time > self.conf.general_climb.get_single_limit_time(
+            #         self.climb_type, timedelta(days=1)):
+            #     logger.attr(self.climb_type, 'Time limit arrived, close current battle')
+            #     self.exit_battle(skip_first=True)
+            #     ok_cnt += 1
+            #     continue
             # 战斗中随机滑动
             # 战斗中随机滑动
-            if random_click_swipt_enable:
+            if ok_cnt == 0 and random_click_swipt_enable:
                 self.random_click_swipt()
                 self.random_click_swipt()
         return True
         return True
 
 
-    def switch_soul(self, conf: SwitchSoulConfig):
-        """
-        根据当前爬塔类型自动切换御魂
-        :param conf: 切换御魂配置
-        :return:
-        """
-        if self.check(Status.ALREADY_SWITCH_SOUL):
-            return
-        self.put_check(Status.ALREADY_SWITCH_SOUL, True)
+    def switch_soul(self, enter_button: RuleImage, cur_img: RuleImage):
+        conf = self.conf.switch_soul_config
+        conf.validate_switch_soul()
         enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
         enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
         enable_by_name = getattr(conf, f"enable_switch_{self.climb_type}_by_name", False)
         enable_by_name = getattr(conf, f"enable_switch_{self.climb_type}_by_name", False)
-        if enable_switch or enable_by_name:
-            self.ui_goto(game.page_shikigami_records)
+        if not enable_switch and not enable_by_name:
+            return
+        self.ui_click(enter_button, stop=self.I_CHECK_RECORDS, interval=1)
         if enable_by_name:
         if enable_by_name:
-            group_name = getattr(conf, f"{self.climb_type}_group_team_name", '-1,-1')
-            if not group_name or len(group_name.split(',')) != 2:
-                raise ValueError('switch soul by name must be 2 length')
-            group, team = group_name.split(",")
+            group, team = getattr(conf, f"{self.climb_type}_group_team_name").split(",")
             self.run_switch_soul_by_name(group, team)
             self.run_switch_soul_by_name(group, team)
         elif enable_switch:
         elif enable_switch:
-            group_team = getattr(conf, f"{self.climb_type}_group_team", '-1,-1')
+            group_team = getattr(conf, f"{self.climb_type}_group_team")
             self.run_switch_soul(group_team)
             self.run_switch_soul(group_team)
-        self.goto_act()
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=cur_img, interval=1)
 
 
     def lock_team(self, battle_conf: GeneralBattleConfig):
     def lock_team(self, battle_conf: GeneralBattleConfig):
         """
         """
         根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
         根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
-        :param battle_conf: 战斗配置
-        :return:
         """
         """
-        if self.check(Status.ALREADY_LOCK_TEAM):
-            return
-        self.put_check(Status.ALREADY_LOCK_TEAM, True)
         enable_preset = getattr(battle_conf, f"enable_{self.climb_type}_preset", False)
         enable_preset = getattr(battle_conf, f"enable_{self.climb_type}_preset", False)
         if not enable_preset:
         if not enable_preset:
             logger.info(f'Lock {self.climb_type} team')
             logger.info(f'Lock {self.climb_type} team')
-            while 1:
-                self.screenshot()
-                if self.appear_then_click(self.I_UNLOCK, interval=1):
-                    continue
-                if self.appear(self.I_LOCK):
-                    return
-        logger.info(f'Unlock {self.climb_type} team')
-        while 1:
-            self.screenshot()
-            if self.appear_then_click(self.I_LOCK, interval=1):
-                continue
-            if self.appear(self.I_UNLOCK):
-                break
-
-    def switch_buff(self, climb_conf: GeneralClimb):
-        if self.check(Status.ALREADY_SWITCH_BUFF):
+            self.ui_click(self.I_UNLOCK, stop=self.I_LOCK, interval=1)
             return
             return
-        self.put_check(Status.ALREADY_SWITCH_BUFF, True)
-        buffs = getattr(climb_conf, f'{self.climb_type}_buff', None)
-        if not buffs or len(buffs.split(',')) == 1:
-            logger.info('Not set buff, skip')
-            return
-        buff_list = [buff.strip() for buff in buffs.split(',')]
-        if not buff_list:
-            logger.info('Buff incorrect formatting, skip')
-            return
-        buff_box_list = [self.C_BUFF_1_BOX, self.C_BUFF_2_BOX]
-        buff_box_empty_list = [self.I_BUFF_BOX_1_EMPTY, self.I_BUFF_BOX_2_EMPTY]
-        buff_up_map = {
-            'buff_1': self.C_BUFF_1_UP,
-            'buff_2': self.C_BUFF_2_UP,
-            'buff_3': self.C_BUFF_3_UP,
-            'buff_4': self.C_BUFF_4_UP,
-            'buff_5': self.C_BUFF_5_UP
-        }
-        logger.info(f'start switch {self.climb_type} {buff_list}')
-        for i, buff_box in enumerate(buff_box_list):
-            logger.info(f'Start down {buff_list[i]}')
-            ok = 0
-            while ok <= 3:
-                self.screenshot()
-                # 打开buff面板
-                self.click(buff_box, interval=1.5)
-                ok = (ok + 1) if self.appear(buff_box_empty_list[i]) else 0
-                # 卸下buff
-                self.appear_then_click(self.I_BUFF_DOWN, interval=0.5)
-            logger.info(f'Down {buff_list[i]} ok')
-        for i, buff_box in enumerate(buff_box_list):
-            logger.info(f'Start up {buff_list[i]}')
-            ok = 0
-            while ok <= 3:
-                self.screenshot()
-                # 打开buff面板
-                self.click(buff_box, interval=1.5)
-                ok = (ok + 1) if not self.appear(buff_box_empty_list[i]) else 0
-                # 装上buff
-                self.appear_then_click(self.I_BUFF_UP, buff_up_map[buff_list[i]], interval=0.5)
-            logger.info(f'Up {buff_list[i]} ok')
-
-    def get_count(self) -> int:
-        """
-        获取当前爬塔类型运行次数
-        :return: 运行次数
-        """
-        return self.count_map[self.climb_type]
+        logger.info(f'Unlock {self.climb_type} team')
+        self.ui_click(self.I_LOCK, stop=self.I_UNLOCK, interval=1)
 
 
-    def check_can_run(self) -> bool:
+    def check_tickets_enough(self) -> bool:
         """
         """
-        判断当前爬塔类型能否运行
-        pass: 剩余门票爬塔票数>0
-        ap: 剩余体力爬塔票数>0
-        boss: 剩余挑战次数>0
+        判断当前爬塔门票是否足够
         :return: True 可以运行 or False
         :return: True 可以运行 or False
         """
         """
-        logger.hr(f'Check the {self.climb_type}', 3)
-        if not self.wait_until_appear(self.O_FIRE, wait_time=5):
-            logger.info(f'Detect fire fail, try next')
-            self.put_check(Status.DOWN, True)
+        logger.hr(f'Check {self.climb_type} tickets')
+        if not self.wait_until_appear(self.O_FIRE, wait_time=3):
+            logger.warning(f'Detect fire fail, try reidentify')
             return False
             return False
         self.screenshot()
         self.screenshot()
         remain_times = 0
         remain_times = 0
         if self.climb_type == 'pass':
         if self.climb_type == 'pass':
-            remain_times = self.O_REMAIN_AP_ACTIVITY2.ocr_digit(
-                _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP_ACTIVITY2))
+            remain_times = self.O_REMAIN_PASS.ocr_digit(
+                _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_PASS))
         if self.climb_type == 'ap':
         if self.climb_type == 'ap':
             remain_times = self.O_REMAIN_AP.ocr_digit(
             remain_times = self.O_REMAIN_AP.ocr_digit(
                 _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP))
                 _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP))
         if self.climb_type == 'boss':
         if self.climb_type == 'boss':
             _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
             _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
-        self.put_check(Status.DOWN, remain_times <= 0)
+        if self.climb_type == 'ap100':
+            remain_times = self.O_REMAIN_AP100.ocr_digit(
+                _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP100))
         return remain_times > 0
         return remain_times > 0
 
 
-    def get_limit(self, climb_conf: GeneralClimb) -> int:
-        """
-        获取配置中当前爬塔类型次数限制
-        :param climb_conf: 爬塔配置
-        :return: 限制次数
-        """
-        limit = getattr(climb_conf, f'{self.climb_type}_limit', 0)
-        return 0 if not limit else limit
-
-    def switch_next(self):
-        """
-        切换下一种爬塔类型
-        :return: True 切换成功 or False
-        """
-        self.run_idx += 1
-        climb_type_list = get_run_order_list(self.config.activity_shikigami.general_climb)
-        if self.run_idx >= len(climb_type_list):
-            logger.info('All climbing activities have been completed')
-            self.put_check(Status.ALL_DOWN, True)
-            return
-        # 切换爬塔类型了, 恢复所有状态
-        self.climb_type = climb_type_list[self.run_idx]
-        self.current_count = 0
-        self.put_check(Status.ALREADY_SWITCH_SOUL, False)
-        self.put_check(Status.ALREADY_LOCK_TEAM, False)
-        self.put_check(Status.GOTO_ACT_FAILED, False)
-        self.put_check(Status.ENTER_BATTLE_FAILED, False)
-        logger.hr(f'Climb type switch to {self.climb_type}', 2)
-
     def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
     def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
         from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
         from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
-        conf = self.config.activity_shikigami
-        enable_preset = getattr(conf.general_battle, f'enable_{self.climb_type}_preset', False)
-        group_team = getattr(conf.switch_soul_config, f'{self.climb_type}_group_team')
-        if enable_preset and (not group_team or len(group_team.split(',')) != 2):
-            raise ValueError('Enable preset but group team not set correct!')
-        group, team = group_team.split(',')
+        self.conf.validate_switch_preset()
+        enable_preset = getattr(self.conf.general_battle, f'enable_{self.climb_type}_preset', False)
+        group, team = getattr(self.conf.switch_soul_config, f'{self.climb_type}_group_team').split(',')
         return gbc(lock_team_enable=not enable_preset,
         return gbc(lock_team_enable=not enable_preset,
                    preset_enable=enable_preset,
                    preset_enable=enable_preset,
                    preset_group=group if enable_preset else 1,
                    preset_group=group if enable_preset else 1,
                    preset_team=team if enable_preset else 1,
                    preset_team=team if enable_preset else 1,
-                   green_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_green', False),
-                   green_mark=getattr(conf.general_battle, f'{self.climb_type}_green_mark'),
-                   random_click_swipt_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_anti_detect',
+                   green_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_green', False),
+                   green_mark=getattr(self.conf.general_battle, f'{self.climb_type}_green_mark'),
+                   random_click_swipt_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_anti_detect',
                                                      False), )
                                                      False), )
 
 
-    def home_main(self) -> bool:
-        """
-        从庭院到活动的爬塔界面
-        :return:
-        """
-        logger.hr("Enter Shikigami", 2)
-        self.ui_goto(game.page_climb_act)
-
-    def main_home(self) -> bool:
-        """
-        从活动的爬塔界面到庭院
-        :return:
-        """
-        logger.hr("Exit Shikigami", 2)
-        self.ui_get_current_page(False)
-        self.ui_goto(game.page_main)
-
-    def goto_act(self):
-        self.ui_goto(self.page_map[self.climb_type], timeout=20)
-
     def random_reward_click(self, exclude_click: list = None, click_now: bool = True) -> RuleClick:
     def random_reward_click(self, exclude_click: list = None, click_now: bool = True) -> RuleClick:
         """
         """
         随机点击
         随机点击
@@ -476,3 +464,5 @@ if __name__ == '__main__':
     t = ScriptTask(c, d)
     t = ScriptTask(c, d)
 
 
     t.run()
     t.run()
+
+

+ 62 - 0
tasks/ActivityShikigami/script_test.py

@@ -0,0 +1,62 @@
+
+import datetime
+from abc import ABC
+
+from module.config.config import Config
+from module.device.device import Device
+
+from tasks.ActivityShikigami.page import page_climb_act
+from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
+from tasks.ActivityShikigami.script_task import ScriptTask
+
+
+class ImplScriptTask(ScriptTask, ABC):
+    def test_battle_main(self) -> bool:
+        # 从别的地方到活动主页面
+        self.ui_get_current_page()
+        self.ui_goto(page_climb_act)
+        # 从活动主页面到默认战斗页面
+        self.ui_click(self.I_TO_BATTLE_MAIN, stop=self.I_CHECK_BATTLE_MAIN, interval=1)
+        # 从默认战斗页面到式神录 再返回
+        self.ui_click(self.I_BATTLE_MAIN_TO_RECORDS, stop=self.I_CHECK_RECORDS, interval=1)
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_CHECK_BATTLE_MAIN, interval=1)
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
+        return True
+
+
+class ScriptTest:
+    def __init__(self, config: str = 'oas1'):
+        self.config = Config(config)
+        self.device = Device(self.config)
+        self.task = ImplScriptTask(self.config, self.device)
+
+
+if __name__ == '__main__':
+    test = ScriptTest(config='oas1')
+    assert test.task.test_battle_main()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+ 78 - 114
tasks/AreaBoss/script_task.py

@@ -7,6 +7,7 @@ import cv2
 import numpy as np
 import numpy as np
 import random
 import random
 import re
 import re
+from module.atom.click import RuleClick
 from tasks.base_task import BaseTask
 from tasks.base_task import BaseTask
 from tasks.Component.GeneralBattle.general_battle import GeneralBattle
 from tasks.Component.GeneralBattle.general_battle import GeneralBattle
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.game_ui import GameUi
@@ -45,11 +46,10 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
         self.ui_get_current_page()
         self.ui_get_current_page()
         self.ui_goto(page_area_boss)
         self.ui_goto(page_area_boss)
 
 
-        self.open_filter()
         # 已挑战鬼王数量
         # 已挑战鬼王数量
         boss_fought = 0
         boss_fought = 0
         if con.boss_reward:
         if con.boss_reward:
-            if self.fight_reward_boss(): #挑战成功则加一
+            if self.fight_reward_boss():  # 挑战成功则加一
                 boss_fought += 1
                 boss_fought += 1
 
 
         self.open_filter()
         self.open_filter()
@@ -260,125 +260,87 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
     def fight_reward_boss(self):
     def fight_reward_boss(self):
         BOSS_REWARD_PHOTO1 = [self.C_AB_BOSS_REWARD_PHOTO_1, self.C_AB_BOSS_REWARD_PHOTO_2, self.C_AB_BOSS_REWARD_PHOTO_3]
         BOSS_REWARD_PHOTO1 = [self.C_AB_BOSS_REWARD_PHOTO_1, self.C_AB_BOSS_REWARD_PHOTO_2, self.C_AB_BOSS_REWARD_PHOTO_3]
         BOSS_REWARD_PHOTO2 = [self.C_AB_BOSS_REWARD_PHOTO_MINUS_2, self.C_AB_BOSS_REWARD_PHOTO_MINUS_1]
         BOSS_REWARD_PHOTO2 = [self.C_AB_BOSS_REWARD_PHOTO_MINUS_2, self.C_AB_BOSS_REWARD_PHOTO_MINUS_1]
-        filter_statue, bossName = self.get_hot_in_reward() # 获取挑战人数最多的Boss的名字
-        if bossName == "direct_attack":
-            return self.boss_fight(self.I_BATTLE_1, True, fileter_open=False)
-        else:
-            if not filter_statue:
-                self.open_filter()
-            # 滑动到最顶层
-            logger.info("Swipe to top")
-            for i in range(random.randint(1, 3)):
-                self.swipe(self.S_AB_FILTER_DOWN)
-
-            for PHOTO in BOSS_REWARD_PHOTO1:
-                name = self.get_bossName(PHOTO)
-                if self.check_common_chars(str(name), bossName):
-                    return self.boss_fight(PHOTO, True, fileter_open=False)
-                else:
-                    self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
-                    self.open_filter()
-            # 倒数一和二
-            for i in range(random.randint(1, 3)):
-                self.swipe(self.S_AB_FILTER_UP)
-            for PHOTO in BOSS_REWARD_PHOTO2:
-                name = self.get_bossName(PHOTO)
-                if self.check_common_chars(str(name), bossName):
-                    return self.boss_fight(PHOTO, True, fileter_open=False)
-                else:
-                    self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
-                    self.open_filter()
+        need_open_filter, boss_name, photo = self.get_hot_in_reward()  # 获取挑战人数最多的Boss的名字
+        if photo is None or boss_name == '声望不够':
+            return False
+        # 不需要打开筛选界面说明直接找到了目标boss, 直接挑战
+        if not need_open_filter:
+            return self.boss_fight(photo, True, fileter_open=False)
+        # 滑动到最顶层
+        logger.info("Swipe to top")
+        for i in range(random.randint(1, 3)):
+            self.swipe(self.S_AB_FILTER_DOWN)
+        # 遍历所有boss找到名称一致的即目前挑战人数最多的
+        for PHOTO in BOSS_REWARD_PHOTO1:
+            self.open_filter()
+            name = self.get_bossName(PHOTO)
+            if self.check_common_chars(str(name), boss_name):
+                return self.boss_fight(PHOTO, True, fileter_open=False)
+            self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
+        # 倒数一和二
+        for i in range(random.randint(1, 3)):
+            self.swipe(self.S_AB_FILTER_UP)
+        for PHOTO in BOSS_REWARD_PHOTO2:
+            self.open_filter()
+            name = self.get_bossName(PHOTO)
+            if self.check_common_chars(str(name), boss_name):
+                return self.boss_fight(PHOTO, True, fileter_open=False)
+            self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
+        self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
 
 
     def get_hot_in_reward(self):
     def get_hot_in_reward(self):
         """
         """
             返回挑战人数最多的悬赏鬼王
             返回挑战人数最多的悬赏鬼王
-        @return:    index
+        @return: 是否打开筛选界面, boss名称, boss图片的click
         @rtype:
         @rtype:
         """
         """
         self.switch_to_reward()
         self.switch_to_reward()
-        lst = []
-        boosName = []
-        filter_open_flag = False
-        num = self.get_num_challenge(self.C_AB_BOSS_REWARD_PHOTO_1)
-        #如果num为0则不再进行nameOcr
-        if num:
-            if num >= 20000 and not self.appear(self.I_AB_NUM_CHALLENGE_RAIL):
-                logger.info("The number of challenges is enough")
-                return filter_open_flag, str("direct_attack")
-            name = self.get_bossName(self.C_AB_BOSS_REWARD_PHOTO_1)
-        else:
-            name = "声望不够"
-        lst.append(num)
-        boosName.append(name)
-        self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
-        #
-        self.open_filter()
-        num = self.get_num_challenge(self.C_AB_BOSS_REWARD_PHOTO_2)
-        if num:
-            if num >= 20000 and not self.appear(self.I_AB_NUM_CHALLENGE_RAIL):
-                logger.info("The number of challenges is enough")
-                return filter_open_flag, str("direct_attack")
-            name = self.get_bossName(self.C_AB_BOSS_REWARD_PHOTO_1)
-        else:
-            name = "声望不够"
-        boosName.append(name)
-        lst.append(num)
-        self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
-        #
-        self.open_filter()
-        num = self.get_num_challenge(self.C_AB_BOSS_REWARD_PHOTO_3)
-        if num:
-            if num >= 20000 and not self.appear(self.I_AB_NUM_CHALLENGE_RAIL):
-                logger.info("The number of challenges is enough")
-                return filter_open_flag, str("direct_attack")
-            name = self.get_bossName(self.C_AB_BOSS_REWARD_PHOTO_1)
-        else:
-            name = "声望不够"
-        boosName.append(name)
-        lst.append(num)
-        self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
-        #
-        self.open_filter()
-        for i in range(random.randint(1, 3)):
-            self.swipe(self.S_AB_FILTER_UP)
-        self.wait_until_appear(self.C_AB_BOSS_REWARD_PHOTO_MINUS_2, wait_time=1)
-        num = self.get_num_challenge(self.C_AB_BOSS_REWARD_PHOTO_MINUS_2)
-        if num:
-            if num >= 20000 and not self.appear(self.I_AB_NUM_CHALLENGE_RAIL):
-                logger.info("The number of challenges is enough")
-                return filter_open_flag, str("direct_attack")
-            name = self.get_bossName(self.C_AB_BOSS_REWARD_PHOTO_1)
-        else:
-            name = "声望不够"
-        boosName.append(name)
-        lst.append(num)
-        self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
-        #
-        self.open_filter()
-        for i in range(random.randint(1, 3)):
-            self.swipe(self.S_AB_FILTER_UP)
-        self.wait_until_appear(self.C_AB_BOSS_REWARD_PHOTO_MINUS_1, wait_time=1)
-        num = self.get_num_challenge(self.C_AB_BOSS_REWARD_PHOTO_MINUS_1)
-        if num:
-            if num >= 20000 and not self.appear(self.I_AB_NUM_CHALLENGE_RAIL):
-                logger.info("The number of challenges is enough")
-                return filter_open_flag, str("direct_attack")
-            name = self.get_bossName(self.C_AB_BOSS_REWARD_PHOTO_1)
-        else:
-            name = "声望不够"
-            filter_open_flag = True
-        boosName.append(name)
-        lst.append(num)
-        self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
-
-
-        index = 0
-        num = 0
-        for idx, val in enumerate(lst):
-            if val > num:
-                index = idx
-                num = val
-        return filter_open_flag, boosName[index]
+        boss_configs = [
+            {"photo": self.C_AB_BOSS_REWARD_PHOTO_1, "need_swipe": False},
+            {"photo": self.C_AB_BOSS_REWARD_PHOTO_2, "need_swipe": False},
+            {"photo": self.C_AB_BOSS_REWARD_PHOTO_3, "need_swipe": False},
+            {"photo": self.C_AB_BOSS_REWARD_PHOTO_MINUS_2, "need_swipe": True},
+            {"photo": self.C_AB_BOSS_REWARD_PHOTO_MINUS_1, "need_swipe": True},
+        ]
+
+        def check_boss(photo: RuleClick):
+            """
+            检查boss是否满足条件
+            :param photo:
+            :return: 是否满足条件, 挑战数量, boss名称
+            """
+            self.open_filter()
+            num = self.get_num_challenge(photo) or 0
+            if not num:
+                name = '声望不够'
+            else:
+                name = self.get_bossName(photo)
+                if num >= 20000 and not self.appear(self.I_AB_NUM_CHALLENGE_RAIL):
+                    logger.info("The number of challenges is enough")
+                    return True, num, name
+            # 没找到满足的则关闭boss页面
+            self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
+            return False, num, name
+
+        mx_challenge_boss_name = None
+        mx_challenge_num = 0
+        photo = None
+        # 遍历所有boss配置, 找挑战人数最多的boss
+        for cfg in boss_configs:
+            if cfg["need_swipe"]:
+                self.open_filter()
+                for _ in range(random.randint(1, 3)):
+                    self.swipe(self.S_AB_FILTER_UP)
+                self.wait_until_appear(cfg["photo"], wait_time=1)
+            ret, challenge_num, boss_name = check_boss(cfg["photo"])
+            if ret:  # 直接找到满足条件的, 则不需要打开筛选界面直接挑战即可
+                return False, boss_name, cfg["photo"]
+            if challenge_num > mx_challenge_num:
+                mx_challenge_num = challenge_num
+                mx_challenge_boss_name = boss_name
+                photo = cfg['photo']
+                logger.attr(mx_challenge_num, f'Select:{boss_name},{photo.name}')
+        return True, mx_challenge_boss_name if mx_challenge_boss_name else '声望不够', photo if mx_challenge_boss_name else None
 
 
     def get_num_challenge(self, click_area):
     def get_num_challenge(self, click_area):
         """
         """
@@ -442,6 +404,7 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
         pass
         pass
 
 
     def open_filter(self):
     def open_filter(self):
+        """打开筛选界面"""
         logger.info("openFilter")
         logger.info("openFilter")
         self.ui_click(self.I_FILTER, self.I_AB_FILTER_OPENED, interval=3)
         self.ui_click(self.I_FILTER, self.I_AB_FILTER_OPENED, interval=3)
 
 
@@ -464,6 +427,7 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
                 continue
                 continue
 
 
     def switch_to_reward(self):
     def switch_to_reward(self):
+        self.open_filter()
         while 1:
         while 1:
             self.screenshot()
             self.screenshot()
             if self.appear(self.I_AB_FILTER_TITLE_REWARD):
             if self.appear(self.I_AB_FILTER_TITLE_REWARD):

+ 5 - 8
tasks/BondlingFairyland/config_battle.py

@@ -3,12 +3,9 @@
 # github https://github.com/runhey
 # github https://github.com/runhey
 from pydantic import BaseModel, Field
 from pydantic import BaseModel, Field
 
 
-from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType
+from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GeneralBattleConfig
+from tasks.Component.config_base import dynamic_hide
 
 
-class BattleConfig(BaseModel):
-    # 是否开启绿标
-    green_enable: bool = Field(default=False, description='green_enable_help')
-    # 选哪一个绿标
-    green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='green_mark_help')
-    # 是否启动战斗时随机点击或者随机滑动
-    random_click_swipt_enable: bool = Field(default=False, description='random_click_swipt_enable_help')
+
+class BattleConfig(GeneralBattleConfig):
+    hide_fields = dynamic_hide('lock_team_enable', 'preset_enable', 'preset_group', 'preset_team')

+ 4 - 2
tasks/BondlingFairyland/script_task.py

@@ -795,10 +795,12 @@ if __name__ == '__main__':
     from module.config.config import Config
     from module.config.config import Config
     from module.device.device import Device
     from module.device.device import Device
 
 
-    config = Config('SWITCH')
+    config = Config('oas1')
     device = Device(config)
     device = Device(config)
     t = ScriptTask(config, device)
     t = ScriptTask(config, device)
-    t.run()
+    # t.run()
+    t.ui_get_current_page()
+    t.ui_goto(page_bondling_fairyland)
     # image = task.screenshot()
     # image = task.screenshot()
 
 
     # con = config.bondling_fairyland
     # con = config.bondling_fairyland

+ 49 - 15
tasks/Component/BaseActivity/config_activity.py

@@ -2,12 +2,13 @@
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
 from datetime import time, timedelta
 from datetime import time, timedelta
-from pydantic import BaseModel, Field, validator, field_validator
+from pydantic import BaseModel, Field, validator, field_validator, model_validator
 from enum import Enum
 from enum import Enum
 
 
 from module.logger import logger
 from module.logger import logger
 
 
 from tasks.Component.config_base import ConfigBase, TimeDelta, Time
 from tasks.Component.config_base import ConfigBase, TimeDelta, Time
+from typing import Optional
 
 
 
 
 class ApMode(str, Enum):
 class ApMode(str, Enum):
@@ -16,23 +17,14 @@ class ApMode(str, Enum):
 
 
 
 
 class GeneralClimb(ConfigBase):
 class GeneralClimb(ConfigBase):
-    # 限制执行的时间
-    limit_time: Time = Field(default=Time(minute=30), description='限制爬塔运行时间')
-    # 限制门票爬塔的次数
+    limit_time: Time = Field(default=Time(minute=30), description='限制爬塔运行总时间')
+    # boss_limit_time: Time = Field(default=Time(minute=5), description='boss单局限制时间')
     pass_limit: int = Field(default=50, description='门票爬塔的最大次数')
     pass_limit: int = Field(default=50, description='门票爬塔的最大次数')
-    # 限制体力爬塔的次数
     ap_limit: int = Field(default=300, description='体力爬塔的最大次数')
     ap_limit: int = Field(default=300, description='体力爬塔的最大次数')
-    # 限制boss战爬塔的次数
     boss_limit: int = Field(default=20, description='boss战爬塔的最大次数')
     boss_limit: int = Field(default=20, description='boss战爬塔的最大次数')
-    # 启用门票爬塔
-    enable_pass: bool = Field(default=True, description='是否启用门票爬塔')
-    # 启用体力爬塔
-    enable_ap: bool = Field(default=True, description='是否启用体力爬塔')
-    # 启用boss战爬塔
-    enable_boss: bool = Field(default=True, description='是否启用boss战爬塔')
-    # 爬塔运行顺序
-    run_sequence: str = Field(default='pass,boss,ap',
-                              description='爬塔运行顺序,英文逗号分隔,从左到右运行,若没启用自动跳过对应类型(pass:门票,boss:boss战,ap:体力)')
+    ap100_limit: int = Field(default=20, description='100体爬塔的最大次数')
+    run_sequence: str = Field(default='pass,ap100,boss,ap',
+                              description='运行爬塔顺序(pass:门票,ap100:100体,boss:boss战,ap:体力)\n英文逗号分隔,从左到右运行,可自定义执行顺序\n例如:pass,ap100,boss,ap就是门票->100体->boss战->体力')
     # # 门票爬塔buff
     # # 门票爬塔buff
     # pass_buff: str = Field(default='buff_4,buff_5', description='门票爬塔加成,buff1-5,加成页从左往右顺序,清空则不切换加成')
     # pass_buff: str = Field(default='buff_4,buff_5', description='门票爬塔加成,buff1-5,加成页从左往右顺序,清空则不切换加成')
     # # 体力爬塔buff
     # # 体力爬塔buff
@@ -44,6 +36,48 @@ class GeneralClimb(ConfigBase):
     # 点击战斗随机休息
     # 点击战斗随机休息
     random_sleep: bool = Field(default=False, description='是否启用在点击战斗前随机休息')
     random_sleep: bool = Field(default=False, description='是否启用在点击战斗前随机休息')
 
 
+    @property
+    def limit_time_v(self) -> timedelta:
+        if isinstance(self.limit_time, time):
+            return timedelta(hours=self.limit_time.hour, minutes=self.limit_time.minute,
+                             seconds=self.limit_time.second)
+        return self.limit_time
+
+    @property
+    def run_sequence_v(self) -> list[str]:
+        self.valid_run_sequence()
+        return [climb_type.strip() for climb_type in self.run_sequence.split(',')]
+
+    def get_single_limit_time(self, climb_type: str, default: timedelta = None) -> Optional[timedelta]:
+        """
+        获取单局限制时间
+        :param climb_type: 爬塔类型
+        :param default: 默认限制时间
+        :return: 单局限制时间 or default
+        """
+        if not climb_type:
+            return default
+        if getattr(self, f'{climb_type}_limit_time', None) is not None:
+            limit_time = getattr(self, f'{climb_type}_limit_time')
+            if isinstance(limit_time, time):
+                return timedelta(hours=limit_time.hour, minutes=limit_time.minute,
+                                 seconds=limit_time.second)
+            return limit_time
+        return default
+
+    # @model_validator(mode='after')
+    def valid_run_sequence(self):
+        if not self.run_sequence or not self.run_sequence.strip():
+            raise ValueError('run sequence cannot be empty')
+        sequence_list = [climb_type.strip() for climb_type in self.run_sequence.split(',')]
+        if not sequence_list or len(sequence_list) < 1:
+            raise ValueError('run sequence cannot be empty')
+        label_set = {field.replace('_limit', '') for field in self.model_fields if field.endswith('_limit')}
+        for climb_type in sequence_list:
+            if climb_type not in label_set:
+                raise ValueError(f'run sequence can only be one of {", ".join(label_set)}, now is {climb_type}')
+        return self
+
     @validator('limit_time', pre=True, always=True)
     @validator('limit_time', pre=True, always=True)
     def parse_limit_time(cls, value):
     def parse_limit_time(cls, value):
         if isinstance(value, str):
         if isinstance(value, str):

+ 2 - 0
tasks/Component/Buy/assets.py

@@ -28,6 +28,8 @@ class BuyAssets:
 	I_BUY_SUB = RuleImage(roi_front=(467,429,50,48), roi_back=(452,412,85,147), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_sub.png")
 	I_BUY_SUB = RuleImage(roi_front=(467,429,50,48), roi_back=(452,412,85,147), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_sub.png")
 	# 出现用魂玉购买 
 	# 出现用魂玉购买 
 	I_BUY_RMB = RuleImage(roi_front=(610,532,35,32), roi_back=(548,483,178,119), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_rmb.png")
 	I_BUY_RMB = RuleImage(roi_front=(610,532,35,32), roi_back=(548,483,178,119), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_rmb.png")
+	# 购买成功 
+	I_BUY_SUCCESS = RuleImage(roi_front=(512,53,261,44), roi_back=(449,0,405,167), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_success.png")
 
 
 
 
 	# Ocr Rule Assets
 	# Ocr Rule Assets

+ 5 - 1
tasks/Component/Buy/buy.py

@@ -3,6 +3,7 @@
 # github https://github.com/runhey
 # github https://github.com/runhey
 import time
 import time
 
 
+from tasks.GameUi.page import random_click
 from typing import Union
 from typing import Union
 
 
 from module.atom.image import RuleImage
 from module.atom.image import RuleImage
@@ -53,6 +54,10 @@ class Buy(BaseTask, BuyAssets):
                         continue
                         continue
                 return False
                 return False
 
 
+            if self.appear(self.I_BUY_SUCCESS):
+                self.ui_click_until_smt_disappear(random_click(), self.I_BUY_SUCCESS, interval=0.8)
+                logger.info('Get reward success')
+                break
 
 
             if self.ui_reward_appear_click():
             if self.ui_reward_appear_click():
                 while 1:
                 while 1:
@@ -71,7 +76,6 @@ class Buy(BaseTask, BuyAssets):
 
 
         return True
         return True
 
 
-
     def buy_more(self, start_click: Union[RuleImage, RuleOcr, RuleClick],
     def buy_more(self, start_click: Union[RuleImage, RuleOcr, RuleClick],
                  number: int = None):
                  number: int = None):
         """
         """

BIN
tasks/Component/Buy/buy/buy_buy_success.png


+ 9 - 0
tasks/Component/Buy/buy/image.json

@@ -34,5 +34,14 @@
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "出现用魂玉购买"
     "description": "出现用魂玉购买"
+  },
+  {
+    "itemName": "buy_success",
+    "imageName": "buy_buy_success.png",
+    "roiFront": "512,53,261,44",
+    "roiBack": "449,0,405,167",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "购买成功"
   }
   }
 ]
 ]

+ 2 - 0
tasks/Component/GeneralBattle/assets.py

@@ -151,6 +151,8 @@ class GeneralBattleAssets:
 	O_PRESET = RuleOcr(roi=(20,620,60,80), area=(20,620,60,80), mode="Single", method="Default", keyword="预", name="preset")
 	O_PRESET = RuleOcr(roi=(20,620,60,80), area=(20,620,60,80), mode="Single", method="Default", keyword="预", name="preset")
 	# 预设 
 	# 预设 
 	O_PRESET_FULL = RuleOcr(roi=(20,620,60,80), area=(20,620,60,80), mode="Single", method="Default", keyword="预设", name="preset_full")
 	O_PRESET_FULL = RuleOcr(roi=(20,620,60,80), area=(20,620,60,80), mode="Single", method="Default", keyword="预设", name="preset_full")
+	# 已标记 
+	O_BOSS_MARK = RuleOcr(roi=(379,44,50,21), area=(379,44,50,21), mode="Single", method="Default", keyword="已标记", name="boss_mark")
 
 
 
 
 	# Swipe Rule Assets
 	# Swipe Rule Assets

+ 11 - 2
tasks/Component/GeneralBattle/gb/ocr.json

@@ -11,7 +11,7 @@
   {
   {
     "itemName": "preset",
     "itemName": "preset",
     "roiFront": "20,620,60,80",
     "roiFront": "20,620,60,80",
-    "roiBack":  "20,620,60,80",
+    "roiBack": "20,620,60,80",
     "mode": "Single",
     "mode": "Single",
     "method": "Default",
     "method": "Default",
     "keyword": "预",
     "keyword": "预",
@@ -20,10 +20,19 @@
   {
   {
     "itemName": "preset_full",
     "itemName": "preset_full",
     "roiFront": "20,620,60,80",
     "roiFront": "20,620,60,80",
-    "roiBack":  "20,620,60,80",
+    "roiBack": "20,620,60,80",
     "mode": "Single",
     "mode": "Single",
     "method": "Default",
     "method": "Default",
     "keyword": "预设",
     "keyword": "预设",
     "description": "预设"
     "description": "预设"
+  },
+  {
+    "itemName": "boss_mark",
+    "roiFront": "379,44,50,21",
+    "roiBack": "379,44,50,21",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "已标记",
+    "description": "已标记"
   }
   }
 ]
 ]

Некоторые файлы не были показаны из-за большого количества измененных файлов