Compare commits

...
207 Commits
Author SHA1 Message Date
DismissedLight 45f55f94cd part 2 2025-01-21 22:10:50 +08:00
DismissedLight d4aae4508a init test 2025-01-21 17:31:09 +08:00
辉鸭蛋 7f7d28825e fixed #1043 #1044 2025-01-21 02:00:26 +08:00
辉鸭蛋 ccb8025676 auto start capture on solo task start2 #1048 2025-01-21 01:56:42 +08:00
辉鸭蛋 2ff5a8930d Revert "auto start capture on solo task start #1048"
This reverts commit ef92586af6.
2025-01-21 01:46:53 +08:00
辉鸭蛋 ef92586af6 auto start capture on solo task start #1048 2025-01-21 01:43:48 +08:00
辉鸭蛋 bd1702af23 quick tp: support Obsidian Totem Pole 2025-01-21 00:03:05 +08:00
辉鸭蛋 23c922d67a Merge pull request #1039 from Scarlet1ssimo/betterscan
优化锄地战斗后捡掉落物的逻辑
2025-01-20 23:46:23 +08:00
辉鸭蛋 89acd1fc65 fix daily reward 2025-01-20 23:17:59 +08:00
辉鸭蛋 c61691ec1e init key binding on first run 2025-01-20 00:56:12 +08:00
辉鸭蛋 ca96204e01 install path 2025-01-20 00:22:40 +08:00
Scarlet fb61b83df5 remove extra logging; refine comments 2025-01-18 21:30:30 -06:00
Scarlet 79aa1505d3 feature: better scan pick 2025-01-18 21:20:02 -06:00
辉鸭蛋 dcafd64139 save theme 2025-01-18 17:54:59 +08:00
辉鸭蛋 5ab63a9e76 retry for open party choose ui 2025-01-18 15:53:40 +08:00
辉鸭蛋 9ddd3c5564 code clean 2025-01-18 15:12:35 +08:00
辉鸭蛋 a36f938e8a Merge pull request #1025 from mfkvfhpdx/main
路径追踪增加增加  允许在jsScript脚本中启用此路径追踪配置、覆盖JS中的自动战斗配置 。
2025-01-18 15:06:58 +08:00
辉鸭蛋 5a7721c534 Merge pull request #1022 from physligl/main
修复传送时遇到的部分问题
2025-01-18 15:06:49 +08:00
辉鸭蛋 12beabc6a2 fixed #971 2025-01-18 12:25:08 +08:00
辉鸭蛋 3da43f3543 fixed #997 2025-01-18 12:05:58 +08:00
辉鸭蛋 ba3f97c63f pathing: run -> dash
持续跑动改成多次冲刺
2025-01-18 11:16:12 +08:00
zjl f14c61145f 重试时战斗策略不跳过 2025-01-18 09:15:41 +08:00
辉鸭蛋 daf6525172 pathing opt
stop_flying下落后都会有个类似target逼近的过程,path类型节点可以取消这个表现
2025-01-18 01:13:28 +08:00
辉鸭蛋 38ea7833c1 opt
优化月卡的的领取
减少获取历练点的点击次数
2025-01-18 01:08:39 +08:00
辉鸭蛋 39da7b489f lock start 2025-01-18 00:53:47 +08:00
辉鸭蛋 e08b0875ee fix lag 2025-01-17 23:12:14 +08:00
zjl e2d0ca5974 去掉战斗部分,主界面判断,减少误判 2025-01-17 14:07:47 +08:00
秋云 89e00207cb 优化传送到七天神像回血的体验。 2025-01-17 03:27:58 +08:00
辉鸭蛋 02f6309a11 fix auto domain dont walk to F 2025-01-17 01:52:43 +08:00
zjl 1a0d61ac94 路径追踪增加 允许在jsScript脚本中启用此路径追踪配置、覆盖JS中的自动战斗配置 。默认为否,开启后可以使JS脚本中的路径追踪和自动战斗,使用该调度器所配置的参数运行 2025-01-16 23:53:17 +08:00
秋云 1538445990 把原本删除的INF级别时间显示回复,并改为DBG级别。 2025-01-16 10:16:43 +08:00
秋云 8a63ac8914 fix typo. 2025-01-16 08:24:08 +08:00
秋云 c87ba278e9 修复了影向山和太山府附近点错传送锚点的问题。 2025-01-16 08:18:50 +08:00
秋云 55b2b48e43 修改日志中时间的时间显示格式。 2025-01-16 08:16:39 +08:00
秋云 30a1b4d40f Merge branch 'main' of https://github.com/physligl/better-genshin-impact 2025-01-16 01:27:37 +08:00
辉鸭蛋 4f6724613a fix some bug 2025-01-16 01:13:05 +08:00
辉鸭蛋 04399c1780 fix log 2025-01-15 23:44:02 +08:00
辉鸭蛋 48ddd1751c + elemental collect avatar
早柚
2025-01-15 23:18:41 +08:00
辉鸭蛋 ccc5c68c1c auto tcg force check resolution 2025-01-15 01:05:28 +08:00
辉鸭蛋 340c4caf49 fix 4 am skip blessing of the welkin moon 2025-01-15 01:03:16 +08:00
辉鸭蛋 9ef5cff886 0.39.3 2025-01-13 22:55:10 +08:00
秋云 ad4993c3cf Add some comments 2025-01-13 08:38:10 +08:00
秋云 01fe05e0c8 Remove unused code from FeatureStorage.cs 2025-01-13 08:36:03 +08:00
辉鸭蛋 a22002966e auto update 2025-01-13 01:17:11 +08:00
辉鸭蛋 8666c931d9 auto path opt
1. 超时直接放弃路径点
2. 所有时间都现取现用
2025-01-12 22:55:51 +08:00
辉鸭蛋 1b7ea8b16b Merge remote-tracking branch 'origin/main' 2025-01-12 22:29:37 +08:00
辉鸭蛋 5552813d61 more pick black item 2025-01-12 22:08:18 +08:00
辉鸭蛋 5e03a29a8e Merge pull request #996 from mfkvfhpdx/main
功能调整和日志分析增加锄地统计
2025-01-12 22:00:05 +08:00
辉鸭蛋 dd9e700485 more game resolution check 2025-01-12 21:45:02 +08:00
辉鸭蛋 d5838017d7 fix script import bug 2025-01-12 21:09:48 +08:00
mfkvfhpdx 64feced367 Merge branch 'babalae:main' into main 2025-01-11 22:43:53 +08:00
辉鸭蛋 9d504443f7 Merge pull request #1001 from physligl/main
添加路径追踪中输出日志的功能。
2025-01-11 11:04:39 +08:00
秋云 1f70cfb364 Merge branch 'main' of https://github.com/physligl/better-genshin-impact 2025-01-11 01:58:30 +08:00
秋云 5f18901e22 添加路径追踪中输出日志的功能。 2025-01-11 01:58:23 +08:00
mfkvfhpdx c4e2f49f4b Merge branch 'babalae:main' into main 2025-01-11 00:33:16 +08:00
辉鸭蛋 1fe5281018 Merge pull request #994 from atiasn/auto-music
增加所有乐曲达成【大音天籁】
2025-01-11 00:06:03 +08:00
辉鸭蛋 dfc8c61c8d test code 2025-01-11 00:01:02 +08:00
NextKale 21bef81374 remove old code 2025-01-10 22:55:26 +08:00
NextKale a90f22a8d5 music level 2025-01-10 22:52:18 +08:00
mfkvfhpdx 31994ce2f4 更多功能增加脚本仓库入口,方便订阅更新。 2025-01-10 22:00:21 +08:00
mfkvfhpdx b0f0b26092 增加了复制组功能,和根据文件夹更新功能 2025-01-10 21:52:01 +08:00
mfkvfhpdx 58db3ad04c 修正分析计时 2025-01-10 17:54:49 +08:00
mfkvfhpdx b686d88134 日志分析开放更多的天数选择 2025-01-10 17:13:59 +08:00
mfkvfhpdx 017f8ed5b0 调整统计排序 2025-01-10 15:07:30 +08:00
mfkvfhpdx 2c727d5e6d 调整使用真正的gameinfo 2025-01-10 11:08:16 +08:00
mfkvfhpdx ebd8031f2c Merge branch 'main' into main 2025-01-10 10:29:53 +08:00
mfkvfhpdx 7d872704c2 日志分析增加锄地分析,锄地分析基于米游社旅行札记,需要输入token才能看到锄地分析地数据。 2025-01-10 10:25:30 +08:00
辉鸭蛋 6e7c7fb78e eye catching tips 2025-01-10 01:56:19 +08:00
辉鸭蛋 1469da4699 ui #936 2025-01-10 01:32:21 +08:00
辉鸭蛋 fcac4aa811 tp wait 1 min #932 2025-01-10 01:18:40 +08:00
辉鸭蛋 072943baf9 #955 2025-01-10 01:07:15 +08:00
辉鸭蛋 6591c8a387 fixed #951 2025-01-10 01:04:31 +08:00
辉鸭蛋 9f11fc984d add no select domain option 2025-01-10 00:59:31 +08:00
辉鸭蛋 902b319211 触发器触发频率必须大于0 2025-01-10 00:51:35 +08:00
辉鸭蛋 2e27154871 mandatory verification of game resolution
自动战斗 秘境 强制校验游戏分辨率
2025-01-10 00:11:22 +08:00
辉鸭蛋 e2afabc7f6 fixed #988
修复战斗策略参数校验提示在()不存在时未正确展示的问题
2025-01-10 00:04:14 +08:00
辉鸭蛋 7853901137 log text optimization
文本优化(战斗策略文件不存在、sendInput被拦截、路径追踪中战斗策略日志打印修改)
2025-01-09 23:58:28 +08:00
辉鸭蛋 cd3713175a auto pathing: don't get close during the battle.
战斗时不需要接近点位
2025-01-09 23:49:49 +08:00
辉鸭蛋 3f2a3b118a auto pathing: add auto run config
并且枫丹合成台不自动跑步
2025-01-09 23:41:53 +08:00
NextKale 7edd0c2565 music 2025-01-09 21:16:31 +08:00
NextKale 66fc5fc080 music 2025-01-09 21:10:19 +08:00
NextKale a52dddb70a Merge branch 'main' into auto-music 2025-01-09 21:00:53 +08:00
NextKale 2df7598304 Merge branch 'main' of github.com:atiasn/better-genshin-impact 2025-01-09 21:00:18 +08:00
mfkvfhpdx a9d8659be7 界面去除了偏色调整,战斗识别颜色调整为范围白和范围黄。当万叶技能cd大于3秒或当前一人次就结束了战斗(基本为没有怪物情况),则跳过此次万叶也拾取。未知界面检查,支持暂停情况。 2025-01-09 19:25:42 +08:00
辉鸭蛋 74f0aa71c3 Merge pull request #989 from physligl/main
添加日志分析匹配日志文件带后缀的情况。
2025-01-08 23:57:56 +08:00
秋云 3239003b22 Merge branch 'babalae:main' into main 2025-01-08 22:33:35 +08:00
秋云 4415e85856 添加匹配日志文件带后缀的情况。 2025-01-08 22:29:46 +08:00
NextKale 291652d75f Merge branch 'babalae:main' into auto-music 2025-01-08 11:46:38 +08:00
辉鸭蛋 828d673509 Merge pull request #983 from physligl/main
修复地图移动的一些已知问题
2025-01-08 01:16:07 +08:00
秋云 b92c52cb5c 合并。 2025-01-08 00:56:31 +08:00
秋云 e11af29b45 Merge branch 'main' of https://github.com/physligl/better-genshin-impact 2025-01-08 00:54:03 +08:00
秋云 b9dd66f87a 合并。 2025-01-08 00:53:49 +08:00
秋云 65e2da4123 Merge branch 'babalae:main' into main 2025-01-08 00:47:42 +08:00
秋云 a85129b087 修复移动地图时概率持续点击标记。 2025-01-08 00:47:07 +08:00
辉鸭蛋 be31d0962f Merge pull request #976 from Womsxd/fix/nested-directories-installer
fix(Setup): 修复BGI安装包多一层文件夹
2025-01-07 23:34:26 +08:00
NextKale 64efabde8f auto music 2025-01-07 23:06:51 +08:00
NextKale a0993b172b Merge branch 'main' of github.com:atiasn/better-genshin-impact 2025-01-07 22:41:00 +08:00
辉鸭蛋 2a6f8fcab2 Merge pull request #980 from HZYgrandma/patch-5
Update README.md
2025-01-07 16:18:00 +08:00
洪籽阳外婆 887e812b28 Update README.md 2025-01-07 14:57:05 +08:00
Womsxd 48b51a60e1 fix(Setup): 修复BGI安装包多一层文件夹 2025-01-07 11:49:05 +08:00
辉鸭蛋 3fb35051d1 update UnityLogGameLocator 2025-01-07 01:08:52 +08:00
秋云 e2530a1001 Merge branch 'main' of https://github.com/physligl/better-genshin-impact 2025-01-07 01:03:20 +08:00
辉鸭蛋 07b8899a51 auto domain: extend the waiting time 2025-01-07 00:33:21 +08:00
辉鸭蛋 55fb63782e remove force team names 2025-01-07 00:22:51 +08:00
辉鸭蛋 1b46502374 0.39.2 2025-01-07 00:19:07 +08:00
辉鸭蛋 580c4754a4 Merge pull request #914 from mfkvfhpdx/main
路径追踪支持 未知界面检查关闭,主要用来解决狗粮、或锄地捡物品,有小概率误触烹饪界面的问题。
2025-01-07 00:17:03 +08:00
辉鸭蛋 30827b2ff4 fix conflicts 2025-01-07 00:14:39 +08:00
辉鸭蛋 9f46fb00be Merge branch 'main' into main 2025-01-07 00:12:41 +08:00
辉鸭蛋 b0236a7a04 Merge pull request #956 from Ayu0K/feat/key-binding-config
[feature] 添加按键绑定自定义功能
2025-01-07 00:09:38 +08:00
Ayu0K 608f135640 mod: 修改打开派蒙界面的按键,使其支持改键 2025-01-06 23:59:55 +08:00
辉鸭蛋 b776ec73a4 Merge pull request #973 from chisato2233/main
美化了部分窗口表现
2025-01-06 23:46:51 +08:00
Ayu0K 2bf74c466b fix: 删除了中途更改全局改键功能的实现方式时遗留的无用代码 2025-01-06 23:30:36 +08:00
辉鸭蛋 76829bd3e1 Merge branch 'main' into feat/key-binding-config 2025-01-06 23:24:09 +08:00
Ayu0K 00ece6ce7a mod: 修改了界面绑定设置UI的描述 2025-01-06 22:55:08 +08:00
Ayu0K 71876a5e65 mod: 更改开书按键 2025-01-06 22:55:08 +08:00
Ayu0K 89109958a2 mod: 更改纪行按键 2025-01-06 22:55:08 +08:00
Ayu0K d179eb9949 mod: 修改剧情选项交互按键 2025-01-06 22:55:08 +08:00
Ayu0K be98f10851 mod: 修改按键方式 2025-01-06 22:55:08 +08:00
Ayu0K 6067058530 mod: 更改移动、跳跃、下落的方式 2025-01-06 22:55:08 +08:00
Ayu0K 19f1315d0a mod: 更改打开任务菜单、开启任务追踪、控制角色前进的方法 2025-01-06 22:55:08 +08:00
Ayu0K 56e4dc2dd6 mod: 修改控制角色前进的方法 2025-01-06 22:55:08 +08:00
Ayu0K e37be52f0e mod: 修改向前移动和跳起的方式 2025-01-06 22:55:08 +08:00
Ayu0K 543e36f77e mod: 更改打开地图的方式 2025-01-06 22:55:08 +08:00
Ayu0K 3b54844e6b mod: 修改打开背包的方式 2025-01-06 22:55:08 +08:00
Ayu0K 8822346f3b mod: 修改ScanPickTask控制角色向前的方式 2025-01-06 22:55:08 +08:00
Ayu0K d54d31454d mod: 修改SwitchPartyTask打开编队界面的方式 2025-01-06 22:55:08 +08:00
Ayu0K 5f525f82d7 mod: 修改QuickSereniteaPotTask发送虚拟按键的方式 2025-01-06 22:55:08 +08:00
Ayu0K f78d7bfcec mod: 修改PathExecutor发送虚拟按键的方式 2025-01-06 22:55:08 +08:00
Ayu0K 2e331dbbc6 fix: 修改了KeyBindingSettingModel的命名空间 2025-01-06 22:55:08 +08:00
Ayu0K f77251551e mod: 修改115行中写死的VK_F为PickVK 2025-01-06 22:55:08 +08:00
Ayu0K 68d6cb18ef mod: 替换为使用扩展方法,不直接调用SimulateKeyHelper 2025-01-06 22:55:07 +08:00
Ayu0K 6d430429f7 add: 为GIActions扩展转换为KeyId的方法 2025-01-06 22:55:07 +08:00
Ayu0K bd811b1bdf mod: 使用新方案替代直接从KeyBindingsConfig中取值 2025-01-06 22:55:07 +08:00
Ayu0K 15f363196c mod: 使用新方案替代直接从KeyBindings中读取按键 2025-01-06 22:55:07 +08:00
Ayu0K c904ae5150 mod: 使用新方案改写自动战斗逻辑Avatar 2025-01-06 22:55:07 +08:00
Ayu0K c7e2d83fb8 mod: 使用新方案改写AutoFightTask 2025-01-06 22:55:07 +08:00
Ayu0K a11639f243 mod: 使用新的方案改写AutoDomain 2025-01-06 22:55:07 +08:00
Ayu0K 19558c9c53 add&mod: 将SimulateAction改为扩展方法,不再继承PostMessageSimulator和InputSimulatorExtension;对于部分不支持的按键和功能(如PostMessageSimulator中的鼠标侧键)予以忽略处理 2025-01-06 22:55:07 +08:00
Ayu0K b183762df7 行尾字符标准化 2025-01-06 22:55:07 +08:00
Ayu0K b32b0f8af1 fix: 监听按键松开时未使用配置的值 2025-01-06 22:55:07 +08:00
Ayu0K daf2b3d1ba add: 添加Simulation2用于根据需要的操作进行按键 2025-01-06 22:55:07 +08:00
Ayu0K c4b705c350 mod: 修改UpDownGrabLeaf中的抓取四叶印(某些模式下的交互)按键,直接使用KeyBindingsConfig中的值 2025-01-06 22:55:07 +08:00
Ayu0K e7d76cdae1 mod: 修改PickAroundHandler,直接使用KeyBindings中的值 2025-01-06 22:55:07 +08:00
Ayu0K 8d577050d1 mod: 修改NahidaCollectHandler中元素战技的按键,直接从KeyBindingsConfig中获取值 2025-01-06 22:55:07 +08:00
Ayu0K 242832edc9 mod: 修改ElementalSkillHandler使用的按键,直接获取KeyBindingsConfig中的值 2025-01-06 22:55:07 +08:00
Ayu0K e39eb9ef93 mod: 修改AutoFight下Avatar(角色战斗逻辑)中的按键,由于该类不是Base On ISoloTask接口的,因此将读取配置文件的操作放在构造函数中。 2025-01-06 22:55:07 +08:00
Ayu0K 2db2c1957a mod: 为连发功能提供改键支持 2025-01-06 22:55:07 +08:00
Ayu0K 60ccbfbace fix: 删除不需要的异常处理结构 2025-01-06 22:55:07 +08:00
Ayu0K 5786ba7634 mod: 修改提示文本 2025-01-06 22:55:07 +08:00
Ayu0K bc6970b6c5 mod: 更改KeyBindingTextBox的行为,在获得焦点时显示输入提示,并忽略取得焦点前的鼠标左键单击事件 2025-01-06 22:55:07 +08:00
Ayu0K 06ee8ab1cc mod: 修改了注释 2025-01-06 22:55:07 +08:00
Ayu0K ac866f9293 fix: 按键名称Unknown 2025-01-06 22:55:07 +08:00
Ayu0K ca3b31f84e mod: 将按键设置与VK解耦合,并提供KeyId向WPF按键、WPF鼠标按键以及VK的互相转换。 2025-01-06 22:55:07 +08:00
Ayu0K a80f6fc423 fix: 修改VK_OEM_PLUS对应的按键名称 2025-01-06 22:55:07 +08:00
Ayu0K 4cfff57b2c mod: 修改AutoFightTask中检测战斗结束使用的打开编队界面和取消攀爬的按键为KeyBindingsConfig记录的按键;修改方案参考AutoWood,在调用Start方法时将该模块需要用到的按键从KeyBindingsConfig中取出 2025-01-06 22:55:07 +08:00
Ayu0K 114a84a9e8 fix: 修正默认的编队键位 2025-01-06 22:55:07 +08:00
Ayu0K 9fa2bcb5a7 mod: 将AutoDomain启动秘境与领取奖励的识别目标和拾取按键与AutoPick统一 2025-01-06 22:55:07 +08:00
Ayu0K 5d80d6d53b mod: 修改AutoDomain中角色移动(用于支持非QWERTY布局的键盘)、冲刺、吃药的按键为KeyBindingsConfig记录的按键;修改方案参考AutoWood,在调用Start方法时将该模块需要用到的按键从KeyBindingsConfig中取出 2025-01-06 22:55:07 +08:00
Ayu0K 5a19b7d2ef mod: 将AutoDomain启动秘境与领取奖励的识别目标和拾取按键与AutoPick统一 2025-01-06 22:55:07 +08:00
Ayu0K accd0280bb add: 添加从注册表中读取按键的功能(待完善:星之归还、隐藏UI按键无法获取;拾取按键、派蒙菜单按键可能存在错误) 2025-01-06 22:55:07 +08:00
Ayu0K 317a526f16 add: 按键绑定的GUI实现(初步) 2025-01-06 22:55:07 +08:00
Ayu0K 8dd6131c94 add: 集成按键绑定配置 2025-01-06 22:55:07 +08:00
Feiran Zhang 0a04734a40 添加茜特菈莉作为循环短E角色 2025-01-06 22:55:07 +08:00
辉鸭蛋 38e5de35a2 Delete 1岩水雷火四神.txt 2025-01-06 22:55:07 +08:00
洪籽阳外婆 5353231810 Update README.md
Update Screenshot
2025-01-06 22:55:07 +08:00
秋云 476f36a19a 确保传送任务开始前一定位于地图界面。 2025-01-06 22:55:07 +08:00
Baisbt 8a6bb597c4 Add files via upload 2025-01-06 22:55:07 +08:00
masm611 b90a6c4227 修正windows10_1909版本WGC故障
windows10_1909版本的WGC不支持IsCursorCaptureEnabled,加了个动态判断防止异常与抓屏失败等。
但是这样就有可能会抓到光标导致图像识别失败,但是个人认为瘦死的骆驼比马大,没有这个api就不调用即可,好歹还能用一下
如果有必要,后面可以考虑加一个弹窗警告一下啥的,但是这样可能会让用户糟心,总不能逼人家换个系统吧?但是不弹窗呢又好像向用户隐藏了某些可能存在的错误,好像又不太对啥的。
只能说云原神的限制还是大了一点,要不要加弹窗我无法决策,还是由大佬来吧
2025-01-06 22:55:07 +08:00
辉鸭蛋 0650bebefa fix genshin install path get 2025-01-06 22:55:07 +08:00
__Chisato__ 6536cad9fd 增加了更改窗口模糊的选项 2025-01-06 20:11:51 +08:00
__Chisato__ 63d7d230dc 优化了PickerWindow的表现效果 2025-01-06 18:35:11 +08:00
zjl abea63bcda Merge branch 'main' of https://github.com/mfkvfhpdx/better-genshin-impact 2025-01-06 14:24:16 +08:00
zjl 653df2f7cc 去掉一个信息提示 2025-01-06 14:22:34 +08:00
zjl ebc8870478 调度器,更多功能中增加日志分析,以列表形式展示配置组耗时和拾取物。 2025-01-06 14:20:05 +08:00
mfkvfhpdx 958c5ab7cd Merge branch 'babalae:main' into main 2025-01-06 14:08:08 +08:00
秋云 99831beb40 修复了地图移动的时候狂点标记问题,修复了移动次数从0开始计算的问题。 2025-01-06 11:51:14 +08:00
辉鸭蛋 a7fae09464 Merge pull request #969 from zhangfeiran/patch-1
添加茜特菈莉作为循环短E角色
2025-01-06 03:22:11 +08:00
Feiran Zhang 57a83cc171 添加茜特菈莉作为循环短E角色 2025-01-06 03:00:04 +08:00
辉鸭蛋 f0af8134ce Delete 1岩水雷火四神.txt 2025-01-05 19:09:59 +08:00
辉鸭蛋 463555c054 Merge pull request #960 from HZYgrandma/patch-3
Update README.md
2025-01-05 18:58:19 +08:00
洪籽阳外婆 01eaa190d8 Update README.md
Update Screenshot
2025-01-05 18:54:35 +08:00
辉鸭蛋 0c487dafd4 Merge pull request #948 from physligl/main
确保传送任务开始前一定位于地图界面。
2025-01-05 17:39:48 +08:00
zjl 1f6e3b78a5 去掉异常处理中的派蒙检查,对于战斗脚本,结束后会误触发 2025-01-05 15:08:50 +08:00
辉鸭蛋 a7da741342 Merge remote-tracking branch 'origin/main' 2025-01-05 14:58:58 +08:00
辉鸭蛋 a57aed9ce7 fix genshin install path get 2025-01-05 14:57:54 +08:00
zjl aa164adb52 Merge remote-tracking branch 'origin/main' 2025-01-05 14:57:46 +08:00
zjl e8b939fbee 未知界面检查常驻于pathing中,去除了该可配置项,以支持js中的路径追踪。pathing逻辑用try块包了起来,最后finally保证,额外开启的线程必定关闭。异常界面检查,当不存在派蒙时尝试按ESC(即使判断错误,也会由未知界面检查,关闭该弹出)。 2025-01-05 14:57:32 +08:00
mfkvfhpdx d872b511d0 Merge branch 'babalae:main' into main 2025-01-05 14:31:16 +08:00
辉鸭蛋 c2dbbe85cd Merge pull request #949 from Baisbt/main
战斗脚本:岩水雷火四神
2025-01-05 13:09:35 +08:00
辉鸭蛋 a75cc84773 Merge pull request #954 from masm611/main
修正windows10_1909版本WGC故障
2025-01-05 13:05:02 +08:00
masm611 1ceb991c1b 修正windows10_1909版本WGC故障
windows10_1909版本的WGC不支持IsCursorCaptureEnabled,加了个动态判断防止异常与抓屏失败等。
但是这样就有可能会抓到光标导致图像识别失败,但是个人认为瘦死的骆驼比马大,没有这个api就不调用即可,好歹还能用一下
如果有必要,后面可以考虑加一个弹窗警告一下啥的,但是这样可能会让用户糟心,总不能逼人家换个系统吧?但是不弹窗呢又好像向用户隐藏了某些可能存在的错误,好像又不太对啥的。
只能说云原神的限制还是大了一点,要不要加弹窗我无法决策,还是由大佬来吧
2025-01-05 12:53:03 +08:00
NextKale 1226f85196 Merge branch 'main' of github.com:atiasn/better-genshin-impact 2025-01-05 11:35:09 +08:00
Baisbt e3a5c491be Add files via upload 2025-01-05 02:36:00 +08:00
秋云 7137e52605 确保传送任务开始前一定位于地图界面。 2025-01-05 01:57:16 +08:00
zjl 3174dc75c8 删除了错误的注释 2025-01-03 20:51:25 +08:00
zjl 4c0d9955b3 阵亡后,重试该路线。但重试,准备传回来时,有几率未打开地图界面,导致传送失败,所以加了每次重试都检查是否打开地图界面。 2025-01-03 20:50:50 +08:00
zjl 8345eb4bdc Merge remote-tracking branch 'origin/main' 2025-01-03 20:14:07 +08:00
zjl 57953933d3 由于地图关闭按钮和烹饪关闭按钮一样,无法作为通用判断,所以依旧使用单个界面检查,调整了检查烹饪的图片范围,增加了按ESC出uid的那个界面也会ESC返回,未知界面检查默认开启。 2025-01-03 20:13:51 +08:00
mfkvfhpdx a0af8405b7 Merge branch 'babalae:main' into main 2025-01-03 08:32:50 +08:00
mfkvfhpdx 3d775241cc Merge branch 'babalae:main' into main 2025-01-02 07:30:31 +08:00
zjl b52af1e9a7 把检查移入pathing中,对烹饪做了二次判断,第一可能会在战斗时,误判 2025-01-01 22:15:53 +08:00
mfkvfhpdx 942bb3a6dd Merge branch 'babalae:main' into main 2025-01-01 20:56:24 +08:00
zjl 3eecea21aa 路径追踪支持 未知界面检查关闭,主要用来解决狗粮、或锄地捡物品,有小概率误触烹饪界面的问题。 2025-01-01 20:54:19 +08:00
zjl ed3cbd47f5 当最后出招人为万叶,并且剩余cd>3时,跳过此次万叶拾取 2024-12-31 22:33:45 +08:00
NextKale d17a29890f Merge branch 'main' of github.com:atiasn/better-genshin-impact 2024-08-16 08:01:16 +08:00
NextKale af86c1147c Merge branch 'main' of github.com:atiasn/better-genshin-impact 2024-07-13 15:37:15 +08:00
NextKale 1c5fe7ec64 wood 2024-06-19 08:57:35 +08:00
156 changed files with 7518 additions and 982 deletions

No files matched your search

+1
View File
@@ -29,3 +29,4 @@ node_modules/
# Rider
.idea
_ReSharper.Caches/
@@ -0,0 +1,19 @@
<Project Sdk="MSTest.Sdk/3.6.4">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UseVSTest>true</UseVSTest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BetterGenshinImpact.CombatScript\BetterGenshinImpact.CombatScript.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,52 @@
namespace BetterGenshinImpact.CombatScript.Test;
[TestClass]
public sealed class ScriptEmitTest
{
[TestMethod]
public void TestEmit()
{
ScriptUnit scriptUnit = new(
[
new CommentSymbol("测试注释"),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("钟离"), [new SpaceTriviaSymbol()], new(
[
new WalkSymbol(WalkDirection.Backward, [new DoubleSymbol(0.1)], [], new CommaTriviaSymbol()),
new SkillSymbol(true, [new HoldSymbol()], [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new WaitSymbol([new DoubleSymbol(0.3)], [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new WalkSymbol(WalkDirection.Forward, [new DoubleSymbol(0.1)], [new SpaceTriviaSymbol()], default),
])),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("芙宁娜"), [new SpaceTriviaSymbol()], new(
[
new SkillSymbol(true, [], new CommaTriviaSymbol()),
new BurstSymbol(true, [new SpaceTriviaSymbol()], default)
])),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("行秋"), [new SpaceTriviaSymbol()], new(
[
new SkillSymbol(true, [], new CommaTriviaSymbol()),
new BurstSymbol(true, [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new SkillSymbol(true, [new SpaceTriviaSymbol()], default),
])),
]);
Console.WriteLine(scriptUnit.Emit(new SymbolEmitter()));
}
[TestMethod]
public void TestParse()
{
ReadOnlySpan<char> raw = """
// 测试注释
钟离 s(0.1),e(hold),wait(0.3),w(0.1)
芙宁娜 e,q
行秋 e,q,e
""";
ScriptUnit scriptUnit = SymbolParser.Parse(raw);
Console.WriteLine(scriptUnit.Emit(new SymbolEmitter()));
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class AttackSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public AttackSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("attack", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public AttackSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("attack", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,24 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class AvatarInstructionListSymbol : BaseSymbol
{
public AvatarInstructionListSymbol(AvatarSymbol avatar, ImmutableArray<TriviaSymbol> triviaList, InstructionListSymbol instructionList)
{
Avatar = avatar;
TriviaList = triviaList;
InstructionList = instructionList;
}
public AvatarSymbol Avatar { get; }
public ImmutableArray<TriviaSymbol> TriviaList { get; }
public InstructionListSymbol InstructionList { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Avatar).Append(TriviaList).Append(InstructionList);
}
}
@@ -0,0 +1,16 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class AvatarSymbol : BaseSymbol
{
public AvatarSymbol(string name)
{
Name = name;
}
public string Name { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Name);
}
}
@@ -0,0 +1,6 @@
namespace BetterGenshinImpact.CombatScript;
public abstract class BaseSymbol : ISymbol
{
public abstract void Emit(ISymbolEmitter emitter);
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -0,0 +1,25 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class BurstSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public BurstSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("burst", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0]);
IsAlias = isAlias;
}
public BurstSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("burst", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "q";
public bool IsAlias { get; }
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class ChargeSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public ChargeSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("charge", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public ChargeSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("charge", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,17 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class CommaTriviaSymbol : TriviaSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(',');
}
}
public sealed class SemicolonTriviaSymbol : TriviaSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(';');
}
}
@@ -0,0 +1,16 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class CommentSymbol : TriviaSymbol
{
public CommentSymbol(string comment)
{
Comment = comment;
}
public string Comment { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append("//").Append(Comment);
}
}
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class DashSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public DashSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("dash", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public DashSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("dash", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,16 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class DoubleSymbol : BaseSymbol, IParameterSymbol
{
public DoubleSymbol(double value)
{
Value = value;
}
public double Value { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Value);
}
}
@@ -0,0 +1,9 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class HoldSymbol : BaseSymbol, IParameterSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append("hold");
}
}
@@ -0,0 +1,8 @@
namespace BetterGenshinImpact.CombatScript;
public interface IInstructionSymbolHasAlias
{
public string AliasName { get; }
public bool IsAlias { get; }
}
@@ -0,0 +1,10 @@
using System;
namespace BetterGenshinImpact.CombatScript;
public interface IInstructionSymbolHasDuration
{
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,5 @@
namespace BetterGenshinImpact.CombatScript;
public interface IParameterSymbol : ISymbol
{
}
@@ -0,0 +1,6 @@
namespace BetterGenshinImpact.CombatScript;
public interface ISymbol
{
void Emit(ISymbolEmitter emitter);
}
@@ -0,0 +1,14 @@
namespace BetterGenshinImpact.CombatScript;
public interface ISymbolEmitter
{
string Emit();
ISymbolEmitter Append(char value);
ISymbolEmitter Append(char value, int repeatCount);
ISymbolEmitter Append(double value);
ISymbolEmitter Append(string value);
}
@@ -0,0 +1,18 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class InstructionListSymbol : BaseSymbol
{
public InstructionListSymbol(ImmutableArray<InstructionSymbol> instructions)
{
Instructions = instructions;
}
public ImmutableArray<InstructionSymbol> Instructions { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Instructions);
}
}
@@ -0,0 +1,59 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public abstract class InstructionSymbol : BaseSymbol
{
protected InstructionSymbol(string name, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
Name = name;
HasParameterList = false;
LeadingTriviaList = leadingTriviaList;
TailingTrivia = tailingTrivia;
}
protected InstructionSymbol(string name, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
Name = name;
HasParameterList = true;
ParameterList = parameterList;
LeadingTriviaList = leadingTriviaList;
TailingTrivia = tailingTrivia;
}
public string Name { get; }
public bool HasParameterList { get; }
public ImmutableArray<IParameterSymbol> ParameterList { get; }
public ImmutableArray<TriviaSymbol> LeadingTriviaList { get; }
public TriviaSymbol? TailingTrivia { get; set; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(LeadingTriviaList);
if (this is IInstructionSymbolHasAlias {IsAlias: true } hasAlias)
{
emitter.Append(hasAlias.AliasName);
}
else
{
emitter.Append(Name);
}
if (HasParameterList)
{
emitter.Append('(');
emitter.Append(ParameterList);
emitter.Append(')');
}
if (TailingTrivia is not null)
{
emitter.Append(TailingTrivia);
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Frozen;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public static class InstructionThrowHelper
{
public static void ThrowIfParameterListIsDefault(ImmutableArray<IParameterSymbol> parameterList)
{
if (parameterList.IsDefault)
{
throw new ArgumentException($"Parameter list can not be default.");
}
}
public static void ThrowIfParameterListCountNotCorrect(ImmutableArray<IParameterSymbol> parameterList, FrozenSet<int> allowedCounts)
{
if (!allowedCounts.Contains(parameterList.Length))
{
throw new ArgumentException($"Instruction parameter count not correct.");
}
}
public static void ThrowIfParameterAtIndexIsNot<T>(ImmutableArray<IParameterSymbol> parameterList, int index, out T symbol)
where T : IParameterSymbol
{
if (parameterList.Length <= index || parameterList[index] is not T result)
{
throw new ArgumentException($"Instruction's parameter at index {index} must be a {typeof(T).Name}.");
}
symbol = result;
}
}
@@ -0,0 +1,25 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class JumpSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public JumpSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("jump", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0]);
IsAlias = isAlias;
}
public JumpSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("jump", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "j";
public bool IsAlias { get; }
}
@@ -0,0 +1,28 @@
using System;
namespace BetterGenshinImpact.CombatScript;
public class LineBreakTriviaSymbol : TriviaSymbol
{
private readonly string lineBreak;
public LineBreakTriviaSymbol()
{
lineBreak = Environment.NewLine;
}
public LineBreakTriviaSymbol(string lineBreak)
{
if (lineBreak is not ("\r\n" or "\n" or "\r" or ";"))
{
throw new ArgumentException("Invalid line break.");
}
this.lineBreak = lineBreak;
}
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(lineBreak);
}
}
@@ -0,0 +1,23 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class ScriptUnit
{
public ScriptUnit(ImmutableArray<ISymbol> symbols)
{
Symbols = symbols;
}
public ImmutableArray<ISymbol> Symbols { get; }
public string Emit(ISymbolEmitter emitter)
{
foreach (ref readonly ISymbol symbol in Symbols.AsSpan())
{
symbol.Emit(emitter);
}
return emitter.Emit();
}
}
@@ -0,0 +1,30 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class SkillSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public SkillSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("skill", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out HoldSymbol _);
}
IsAlias = isAlias;
}
public SkillSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("skill", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "e";
public bool IsAlias { get; }
}
@@ -0,0 +1,21 @@
namespace BetterGenshinImpact.CombatScript;
public class SpaceTriviaSymbol : TriviaSymbol
{
private readonly int count;
public SpaceTriviaSymbol()
{
count = 1;
}
public SpaceTriviaSymbol(int count)
{
this.count = count;
}
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(' ', count);
}
}
@@ -0,0 +1,37 @@
using System.Text;
namespace BetterGenshinImpact.CombatScript;
public sealed class SymbolEmitter : ISymbolEmitter
{
private readonly StringBuilder builder = new();
public string Emit()
{
return builder.ToString();
}
public ISymbolEmitter Append(char value)
{
builder.Append(value);
return this;
}
public ISymbolEmitter Append(char value, int repeatCount)
{
builder.Append(value, repeatCount);
return this;
}
public ISymbolEmitter Append(double value)
{
builder.Append(value);
return this;
}
public ISymbolEmitter Append(string value)
{
builder.Append(value);
return this;
}
}
@@ -0,0 +1,23 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public static class SymbolEmitterExtensions
{
public static ISymbolEmitter Append(this ISymbolEmitter emitter, ISymbol symbol)
{
symbol.Emit(emitter);
return emitter;
}
public static ISymbolEmitter Append<TSymbol>(this ISymbolEmitter emitter, ImmutableArray<TSymbol> symbolList)
where TSymbol : ISymbol
{
foreach(ref readonly TSymbol symbol in symbolList.AsSpan())
{
symbol.Emit(emitter);
}
return emitter;
}
}
@@ -0,0 +1,193 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
namespace BetterGenshinImpact.CombatScript;
public static class SymbolParser
{
public static ScriptUnit Parse(ReadOnlySpan<char> raw)
{
ImmutableArray<ISymbol>.Builder symbols = ImmutableArray.CreateBuilder<ISymbol>();
ParseLines(raw, symbols);
return new(symbols.ToImmutable());
}
private static void ParseLines(ReadOnlySpan<char> raw, ImmutableArray<ISymbol>.Builder symbols)
{
bool skipNextRange = false;
ref readonly char end = ref raw[^1];
foreach(Range range in raw.SplitAny(['\r', '\n', ';']))
{
if (skipNextRange)
{
skipNextRange = false;
continue;
}
int offset = range.End.GetOffset(raw.Length);
if (offset >= raw.Length)
{
break;
}
ref readonly char peek = ref raw[offset];
LineBreakTriviaSymbol lineBreakTrivia;
if (peek is '\r')
{
if (Unsafe.IsAddressLessThan(in peek, in end) && Unsafe.Add(ref Unsafe.AsRef(in peek), 1) is '\n')
{
// It's a CRLF
lineBreakTrivia = new("\r\n");
skipNextRange = true;
}
else
{
// It's a CR
lineBreakTrivia = new("\r");
}
}
else if (peek is '\n')
{
// It's a LF
lineBreakTrivia = new("\n");
}
else if (peek is ';')
{
lineBreakTrivia = new(";");
}
else
{
throw new InvalidOperationException($"Failed to parse line break trivia at {range}.");
}
if (ParseLine(raw[range]) is { } symbol)
{
symbols.Add(symbol);
}
symbols.Add(lineBreakTrivia);
}
}
private static ISymbol? ParseLine(ReadOnlySpan<char> raw)
{
if (raw.IsEmpty)
{
return default;
}
if (raw.StartsWith("//"))
{
return new CommentSymbol(raw[2..].ToString());
}
int indexOfSpace = raw.IndexOf(' ');
ReadOnlySpan<char> avatarIdentifier = raw[..indexOfSpace];
AvatarSymbol avatarSymbol = new(avatarIdentifier.ToString());
ImmutableArray<TriviaSymbol> triviaList = ParseTriviaList(raw[indexOfSpace..], out int advanced);
InstructionListSymbol listSymbol = ParseInstructionList(raw[(indexOfSpace + advanced)..]);
return new AvatarInstructionListSymbol(avatarSymbol, triviaList, listSymbol);
}
private static InstructionListSymbol ParseInstructionList(ReadOnlySpan<char> raw)
{
ImmutableArray<InstructionSymbol>.Builder builder = ImmutableArray.CreateBuilder<InstructionSymbol>();
foreach (Range range in raw.Split(','))
{
ReadOnlySpan<char> current = raw[range];
ImmutableArray<TriviaSymbol> leadingTriviaList = ParseTriviaList(current, out int advanced);
if (ParseInstruction(current[advanced..], leadingTriviaList) is { } symbol)
{
builder.Add(symbol);
}
}
return new(builder.ToImmutable());
}
private static InstructionSymbol? ParseInstruction(ReadOnlySpan<char> raw, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
if (raw.IsEmpty)
{
return default;
}
switch (raw[0])
{
// attack|a
case 'a':
break;
// burst
case 'b':
return new BurstSymbol(false, [], leadingTriviaList, tailingTrivia);
break;
// charge
case 'c':
break;
// dash|d
case 'd':
break;
// jump|j
case 'j':
break;
// q
case 'q':
return new BurstSymbol(true, [], leadingTriviaList, tailingTrivia);
break;
// skill|s
case 's':
break;
// wait|walk|w
case 'w':
break;
}
return default;
}
// Handle ','&' '
private static ImmutableArray<TriviaSymbol> ParseTriviaList(ReadOnlySpan<char> raw, out int advanced)
{
advanced = 0;
if (raw.IsEmpty)
{
return ImmutableArray<TriviaSymbol>.Empty;
}
ImmutableArray<TriviaSymbol>.Builder builder = ImmutableArray.CreateBuilder<TriviaSymbol>();
int spaceCount = 0;
foreach (ref readonly char value in raw)
{
advanced++;
if (value is ' ')
{
spaceCount++;
}
else
{
if (spaceCount is not 0)
{
builder.Add(new SpaceTriviaSymbol(spaceCount));
spaceCount = 0;
}
if (value is ',')
{
builder.Add(new CommaTriviaSymbol());
}
else
{
break;
}
}
}
return builder.ToImmutable();
}
}
@@ -0,0 +1,5 @@
namespace BetterGenshinImpact.CombatScript;
public abstract class TriviaSymbol : BaseSymbol
{
}
@@ -0,0 +1,23 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class WaitSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public WaitSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("wait", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [1]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -0,0 +1,9 @@
namespace BetterGenshinImpact.CombatScript;
public enum WalkDirection
{
Forward,
Backward,
Left,
Right
}
@@ -0,0 +1,70 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class WalkSymbol : InstructionSymbol, IInstructionSymbolHasAlias, IInstructionSymbolHasDuration, IParameterSymbol
{
public WalkSymbol(WalkDirection direction, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [1]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
Direction = direction;
IsAlias = true;
}
// Used for parameter
public WalkSymbol(WalkDirection direction, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", leadingTriviaList, tailingTrivia)
{
Direction = direction;
IsAlias = true;
}
public WalkSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [2]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out WalkSymbol directionAlias);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 1, out DoubleSymbol doubleSymbol);
Direction = directionAlias.Direction;
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
IsAlias = false;
}
public string AliasName
{
get
{
return Direction switch
{
WalkDirection.Forward => "w",
WalkDirection.Backward => "s",
WalkDirection.Left => "a",
WalkDirection.Right => "d",
_ => throw new ArgumentOutOfRangeException(),
};
}
}
public bool IsAlias { get; }
public WalkDirection Direction { get; }
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
+20
View File
@@ -19,6 +19,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Test",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.WindowsInput", "Fischless.WindowsInput\Fischless.WindowsInput.csproj", "{9D00BC7A-9280-4AC9-8951-4502EDB71B76}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.CombatScript", "BetterGenshinImpact.CombatScript\BetterGenshinImpact.CombatScript.csproj", "{57C278F9-F62A-480A-B929-B0E5D8174194}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.CombatScript.Test", "BetterGenshinImpact.CombatScript.Test\BetterGenshinImpact.CombatScript.Test.csproj", "{09427DA8-665E-441A-A576-C11FBC6F9E5C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -83,6 +87,22 @@ Global
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|Any CPU.Build.0 = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.ActiveCfg = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.Build.0 = Release|x64
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|Any CPU.Build.0 = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|x64.ActiveCfg = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|x64.Build.0 = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|Any CPU.ActiveCfg = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|Any CPU.Build.0 = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|x64.ActiveCfg = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|x64.Build.0 = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|x64.ActiveCfg = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|x64.Build.0 = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|Any CPU.Build.0 = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|x64.ActiveCfg = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+2
View File
@@ -77,6 +77,7 @@ public partial class App : Application
services.AddHostedService<ApplicationHostService>();
// Page resolver service
services.AddSingleton<IPageService, PageService>();
services.AddSingleton<IUpdateService, UpdateService>();
// Service containing navigation, same as INavigationWindow... but without window
services.AddSingleton<INavigationService, NavigationService>();
@@ -101,6 +102,7 @@ public partial class App : Application
services.AddView<OneDragonFlowPage, OneDragonFlowViewModel>();
services.AddSingleton<PathingConfigViewModel>();
// services.AddView<PathingConfigView, PathingConfigViewModel>();
services.AddView<KeyBindingsSettingsPage, KeyBindingsSettingsPageViewModel>();
// 一条龙 ViewModels
// services.AddSingleton<CraftViewModel>();
@@ -10,7 +10,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\Images\logo.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.39.1</AssemblyVersion>
<AssemblyVersion>0.39.4</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
@@ -71,7 +71,7 @@
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
<PackageReference Include="WPF-UI" Version="3.0.5" />
<PackageReference Include="WPF-UI.Tray" Version="3.0.5" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.23" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.26" />
<PackageReference Include="YoloV8" Version="4.1.7" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
</ItemGroup>
@@ -7,6 +7,7 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoPick;
using BetterGenshinImpact.GameTask.AutoSkip;
using BetterGenshinImpact.GameTask.AutoWood;
using BetterGenshinImpact.GameTask.AutoMusicGame;
using BetterGenshinImpact.GameTask.QuickTeleport;
using BetterGenshinImpact.Service.Notification;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -132,6 +133,11 @@ public partial class AllConfig : ObservableObject
/// 自动战斗配置
/// </summary>
public AutoFightConfig AutoFightConfig { get; set; } = new();
/// <summary>
/// 自动乐曲配置 - 千音雅集
/// </summary>
public AutoMusicGameConfig AutoMusicGameConfig { get; set; } = new();
/// <summary>
/// 自动秘境配置
@@ -165,6 +171,11 @@ public partial class AllConfig : ObservableObject
/// </summary>
public NotificationConfig NotificationConfig { get; set; } = new();
/// <summary>
/// 原神按键绑定配置
/// </summary>
public KeyBindingsConfig KeyBindingsConfig { get; set; } = new();
[JsonIgnore]
public Action? OnAnyChangedAction { get; set; }
@@ -176,6 +187,7 @@ public partial class AllConfig : ObservableObject
GenshinStartConfig.PropertyChanged += OnAnyPropertyChanged;
NotificationConfig.PropertyChanged += OnAnyPropertyChanged;
NotificationConfig.PropertyChanged += OnNotificationPropertyChanged;
KeyBindingsConfig.PropertyChanged += OnAnyPropertyChanged;
AutoPickConfig.PropertyChanged += OnAnyPropertyChanged;
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
@@ -187,6 +199,7 @@ public partial class AllConfig : ObservableObject
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
@@ -1,5 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using Wpf.Ui.Controls;
namespace BetterGenshinImpact.Core.Config;
@@ -26,4 +27,16 @@ public partial class CommonConfig : ObservableObject
/// </summary>
[ObservableProperty]
private bool _exitToTray;
/// <summary>
/// 主题
/// </summary>
[ObservableProperty]
private WindowBackdropType _currentBackdropType = WindowBackdropType.Mica;
/// <summary>
/// 是否是第一次运行
/// </summary>
[ObservableProperty]
private bool _isFirstRun = true;
}
@@ -0,0 +1,964 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Windows.Forms;
using System.Windows.Input;
using Windows.Networking.PushNotifications;
using static Vanara.PInvoke.User32;
namespace BetterGenshinImpact.Core.Config;
/// <summary>
/// 原神按键绑定配置
/// </summary>
[Serializable]
public partial class KeyBindingsConfig:ObservableObject
{
#region Actions(操作)
/// <summary>
/// 向前移动
/// </summary>
[ObservableProperty]
private KeyId _moveForward = KeyId.W;
/// <summary>
/// 向后移动
/// </summary>
[ObservableProperty]
private KeyId _moveBackward = KeyId.S;
/// <summary>
/// 向左移动
/// </summary>
[ObservableProperty]
private KeyId _moveLeft = KeyId.A;
/// <summary>
/// 向右移动
/// </summary>
[ObservableProperty]
private KeyId _moveRight = KeyId.D;
/// <summary>
/// 切换走/跑;特定操作模式下向下移动
/// </summary>
[ObservableProperty]
private KeyId _switchToWalkOrRun = KeyId.LeftCtrl;
/// <summary>
/// 普通攻击
/// </summary>
[ObservableProperty]
private KeyId _normalAttack = KeyId.MouseLeftButton;
/// <summary>
/// 元素战技
/// </summary>
[ObservableProperty]
private KeyId _elementalSkill = KeyId.E;
/// <summary>
/// 元素爆发
/// </summary>
[ObservableProperty]
private KeyId _elementalBurst = KeyId.Q;
/// <summary>
/// 冲刺(键盘)
/// </summary>
[ObservableProperty]
private KeyId _sprintKeyboard = KeyId.LeftShift;
/// <summary>
/// 冲刺(鼠标)
/// </summary>
[ObservableProperty]
private KeyId _sprintMouse = KeyId.MouseRightButton;
/// <summary>
/// 切换瞄准模式
/// </summary>
[ObservableProperty]
private KeyId _switchAimingMode = KeyId.R;
/// <summary>
/// 跳跃;特定操作模式下向上移动
/// </summary>
[ObservableProperty]
private KeyId _jump = KeyId.Space;
/// <summary>
/// 落下
/// </summary>
[ObservableProperty]
private KeyId _drop = KeyId.X;
/// <summary>
/// 拾取/交互(自动拾取由AutoPick模块管理)
/// </summary>
[ObservableProperty]
private KeyId _pickUpOrInteract = KeyId.F;
/// <summary>
/// 快捷使用小道具
/// </summary>
[ObservableProperty]
private KeyId _quickUseGadget = KeyId.Z;
/// <summary>
/// 特定玩法内交互操作
/// </summary>
[ObservableProperty]
private KeyId _interactionInSomeMode = KeyId.T;
/// <summary>
/// 开启任务追踪
/// </summary>
[ObservableProperty]
private KeyId _questNavigation = KeyId.V;
/// <summary>
/// 中断挑战
/// </summary>
[ObservableProperty]
private KeyId _abandonChallenge = KeyId.P;
/// <summary>
/// 切换小队角色1
/// </summary>
[ObservableProperty]
private KeyId _switchMember1 = KeyId.D1;
/// <summary>
/// 切换小队角色2
/// </summary>
[ObservableProperty]
private KeyId _switchMember2 = KeyId.D2;
/// <summary>
/// 切换小队角色3
/// </summary>
[ObservableProperty]
private KeyId _switchMember3 = KeyId.D3;
/// <summary>
/// 切换小队角色4
/// </summary>
[ObservableProperty]
private KeyId _switchMember4 = KeyId.D4;
/// <summary>
/// 切换小队角色5
/// </summary>
[ObservableProperty]
private KeyId _switchMember5 = KeyId.D5;
/// <summary>
/// 呼出快捷轮盘
/// </summary>
[ObservableProperty]
private KeyId _shortcutWheel = KeyId.Tab;
#endregion
#region Menus(菜单)
/// <summary>
/// 打开背包
/// </summary>
[ObservableProperty]
private KeyId _openInventory = KeyId.B;
/// <summary>
/// 打开角色界面
/// </summary>
[ObservableProperty]
private KeyId _openCharacterScreen = KeyId.C;
/// <summary>
/// 打开地图
/// </summary>
[ObservableProperty]
private KeyId _openMap = KeyId.M;
/// <summary>
/// 打开派蒙界面
/// </summary>
[ObservableProperty]
private KeyId _openPaimonMenu = KeyId.Escape;
/// <summary>
/// 打开冒险之证界面
/// </summary>
[ObservableProperty]
private KeyId _openAdventurerHandbook = KeyId.F1;
/// <summary>
/// 打开多人游戏界面
/// </summary>
[ObservableProperty]
private KeyId _openCoOpScreen = KeyId.F2;
/// <summary>
/// 打开祈愿界面
/// </summary>
[ObservableProperty]
private KeyId _openWishScreen = KeyId.F3;
/// <summary>
/// 打开纪行界面
/// </summary>
[ObservableProperty]
private KeyId _openBattlePassScreen = KeyId.F4;
/// <summary>
/// 打开活动面板
/// </summary>
[ObservableProperty]
private KeyId _openTheEventsMenu = KeyId.F5;
/// <summary>
/// 打开玩法系统界面(尘歌壶内猫尾酒馆内)
/// </summary>
[ObservableProperty]
private KeyId _openTheSettingsMenu = KeyId.F6;
/// <summary>
/// 打开摆设界面(尘歌壶内)
/// </summary>
[ObservableProperty]
private KeyId _openTheFurnishingScreen = KeyId.F7;
/// <summary>
/// 打开星之归还(条件符合期间生效)
/// </summary>
[ObservableProperty]
private KeyId _openStellarReunion = KeyId.F8;
/// <summary>
/// 开关任务菜单
/// </summary>
[ObservableProperty]
private KeyId _openQuestMenu = KeyId.J;
/// <summary>
/// 打开通知详情
/// </summary>
[ObservableProperty]
private KeyId _openNotificationDetails = KeyId.Y;
/// <summary>
/// 打开聊天界面
/// </summary>
[ObservableProperty]
private KeyId _openChatScreen = KeyId.Enter;
/// <summary>
/// 打开特殊环境说明
/// </summary>
[ObservableProperty]
private KeyId _openSpecialEnvironmentInformation = KeyId.U;
/// <summary>
/// 查看教程详情
/// </summary>
[ObservableProperty]
private KeyId _checkTutorialDetails = KeyId.G;
/// <summary>
/// 长按打开元素视野
/// </summary>
[ObservableProperty]
private KeyId _elementalSight = KeyId.MouseMiddleButton;
/// <summary>
/// 呼出鼠标
/// </summary>
[ObservableProperty]
private KeyId _showCursor = KeyId.LeftAlt;
/// <summary>
/// 打开队伍配置界面
/// </summary>
[ObservableProperty]
private KeyId _openPartySetupScreen = KeyId.L;
/// <summary>
/// 打开好友界面
/// </summary>
[ObservableProperty]
private KeyId _openFriendsScreen = KeyId.O;
/// <summary>
/// 隐藏主界面
/// </summary>
[ObservableProperty]
private KeyId _hideUI = KeyId.Slash;
#endregion
}
public static class KeyIdConverter
{
/// <summary>
/// 将KeyId转换为字符串(可在后续支持多语言),按键名称的显示尽量与原神UI一致
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToName(this KeyId value)
{
return ToChineseName(value);
}
private static string ToChineseName(KeyId value)
{
return value switch
{
// 需要单独翻译的按键
KeyId.None => "<未指定>",
KeyId.Unknown => "<未知>",
KeyId.MouseLeftButton => "鼠标左键",
KeyId.MouseRightButton => "鼠标右键",
KeyId.MouseMiddleButton => "鼠标中键",
KeyId.MouseSideButton1 => "鼠标侧键1",
KeyId.MouseSideButton2 => "鼠标侧键2",
KeyId.Apps => "菜单键",
// 无需单独翻译的部分
_ => EnglishKeyNameToChinese(value),
};
}
private static string EnglishKeyNameToChinese(KeyId value)
{
var engName = ToEnglishName(value);
if (engName.StartsWith("Left ") || engName.StartsWith("Right "))
{
return engName.Replace("Left ", "左").Replace("Right ", "右");
}
return engName;
}
private static string ToEnglishName(KeyId value)
{
return value switch
{
// 需要转换的部分
KeyId.None => "<None>",
KeyId.Unknown => "<Unknown>",
KeyId.MouseLeftButton => "Mouse LButton",
KeyId.MouseRightButton => "Mouse RButton",
KeyId.MouseMiddleButton => "Mouse MButton",
KeyId.MouseSideButton1 => "Mouse XButton1",
KeyId.MouseSideButton2 => "Mouse XButton2",
KeyId.Escape => "Esc",
KeyId.PageUp => "Page Up",
KeyId.PageDown => "Page Down",
KeyId.CapsLock => "Caps Lock",
KeyId.ScrollLock => "Scroll Lock",
KeyId.LeftShift => "Left Shift",
KeyId.RightShift => "Right Shift",
KeyId.LeftCtrl => "Left Crtl",
KeyId.RightCtrl => "Right Ctrl",
KeyId.LeftAlt => "Left Alt",
KeyId.RightAlt => "Right Alt",
KeyId.LeftWin => "Left Win",
KeyId.RightWin => "Right Win",
KeyId.Apps => "Menu",
KeyId.Left => "←",
KeyId.Up => "↑",
KeyId.Right => "→",
KeyId.Down => "↓",
KeyId.D0 => "0",
KeyId.D1 => "1",
KeyId.D2 => "2",
KeyId.D3 => "3",
KeyId.D4 => "4",
KeyId.D5 => "5",
KeyId.D6 => "6",
KeyId.D7 => "7",
KeyId.D8 => "8",
KeyId.D9 => "9",
KeyId.Apostrophe => "'",
KeyId.Comma => ",",
KeyId.Minus => "-",
KeyId.Equal => "=",
KeyId.Period => ".",
KeyId.Slash => "/",
KeyId.Backslash => @"\",
KeyId.Semicolon => ";",
KeyId.LeftSquareBracket => "[",
KeyId.RightSquareBracket => "]",
KeyId.Tilde => "`",
KeyId.NumLock => "Num Lock",
KeyId.NumPad0 => "Num 0",
KeyId.NumPad1 => "Num 1",
KeyId.NumPad2 => "Num 2",
KeyId.NumPad3 => "Num 3",
KeyId.NumPad4 => "Num 4",
KeyId.NumPad5 => "Num 5",
KeyId.NumPad6 => "Num 6",
KeyId.NumPad7 => "Num 7",
KeyId.NumPad8 => "Num 8",
KeyId.NumPad9 => "Num 9",
KeyId.Decimal => "Num .",
KeyId.Divide => "Num /",
KeyId.Multiply => "Num *",
KeyId.Subtract => "Num -",
KeyId.Add => "Num +",
KeyId.NumEnter => "Num Enter",
// 默认使用枚举名
_ => value.ToString(),
};
}
/// <summary>
/// 将KeyId转换为VK
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static VK ToVK(this KeyId value)
{
return value switch
{
// 这两个值在VK中没有,抛异常
KeyId.None => throw new ArgumentOutOfRangeException(nameof(value), "未指定按键,无法转换为VK。"),
KeyId.Unknown => throw new ArgumentOutOfRangeException(nameof(value), "未知按键,无法转换为VK。"),
// 剩下的值相同,直接转
_ => (VK)value,
};
}
/// <summary>
/// 将KeyId转换为System.Windows.Input.Key
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Key ToInputKey(this KeyId value)
{
// 部分按键名称相同,使用名称转换
try
{
return Enum.Parse<Key>(value.ToString());
}
catch
{
// 其他键使用查表法转换
return value switch
{
KeyId.LeftWin => Key.LWin,
KeyId.RightWin => Key.RWin,
KeyId.Apostrophe => Key.Oem7,
KeyId.Comma => Key.OemComma,
KeyId.Minus => Key.OemMinus,
KeyId.Equal => Key.OemPlus,
KeyId.Period => Key.OemPeriod,
KeyId.Slash => Key.Oem2,
KeyId.Semicolon => Key.Oem1,
KeyId.LeftSquareBracket => Key.Oem4,
KeyId.Backslash => Key.Oem5,
KeyId.RightSquareBracket => Key.Oem6,
KeyId.Tilde => Key.Oem3,
KeyId.Enter => Key.Enter,
KeyId.ScrollLock => Key.Scroll,
KeyId.PageUp => Key.Prior,
KeyId.PageDown => Key.Next,
KeyId.Backspace => Key.Back,
KeyId.CapsLock => Key.Capital,
// None、Unknown和鼠标按键抛异常
_ => throw new ArgumentOutOfRangeException(nameof(value)),
};
}
}
/// <summary>
/// 将KeyId转换为MouseButton
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static MouseButton ToMouseButton(this KeyId value)
{
return value switch
{
KeyId.MouseLeftButton => MouseButton.Left,
KeyId.MouseRightButton => MouseButton.Right,
KeyId.MouseMiddleButton => MouseButton.Middle,
KeyId.MouseSideButton1 => MouseButton.XButton1,
KeyId.MouseSideButton2 => MouseButton.XButton2,
_ => throw new ArgumentOutOfRangeException(nameof(value), "键盘按键请使用ToInputKey方法"),
};
}
/// <summary>
/// [实验] 将KeyId转换为WinForm中的Keys(用于兼容按键连发功能)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Keys ToWinFormKeys(this KeyId value)
{
try
{
return Enum.Parse<Keys>(value.ToInputKey().ToString());
}
catch
{
return default;
}
}
/// <summary>
/// 将VK转换为KeyId
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static KeyId FromVK(VK value)
{
// 尝试通过VK的值获取KeyId的枚举名。若成功,表示对应的VK在KeyId支持的范围内,直接转换;否则返回Unknown
return string.IsNullOrEmpty(Enum.GetName(typeof(KeyId), value)) ? KeyId.Unknown : (KeyId)value;
}
/// <summary>
/// 将System.Windows.Input.Key转换为KeyId
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static KeyId FromInputKey(Key value)
{
// 部分按键名称相同,使用名称转换
try
{
return Enum.Parse<KeyId>(value.ToString());
}
catch
{
// 其他键使用查表法转换
return value switch
{
Key.LWin => KeyId.LeftWin,
Key.RWin => KeyId.RightWin,
Key.Oem7 => KeyId.Apostrophe,
Key.OemComma => KeyId.Comma,
Key.OemMinus => KeyId.Minus,
Key.OemPlus => KeyId.Equal,
Key.OemPeriod => KeyId.Period,
Key.Oem2 => KeyId.Slash,
Key.Oem1 => KeyId.Semicolon,
Key.Oem4 => KeyId.LeftSquareBracket,
Key.Oem5 => KeyId.Backslash,
Key.Oem6 => KeyId.RightSquareBracket,
Key.Oem3 => KeyId.Tilde,
Key.Enter => KeyId.Enter,
Key.Scroll => KeyId.ScrollLock,
Key.Prior => KeyId.PageUp,
Key.Next => KeyId.PageDown,
Key.Back => KeyId.Backspace,
Key.Capital => KeyId.CapsLock,
// 支持列表外的值返回Unknown
_ => KeyId.Unknown,
};
}
}
/// <summary>
/// 将MouseButton转换为KeyId
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static KeyId FromMouseButton(MouseButton value)
{
return value switch
{
MouseButton.Left => KeyId.MouseLeftButton,
MouseButton.Right => KeyId.MouseRightButton,
MouseButton.Middle => KeyId.MouseMiddleButton,
MouseButton.XButton1 => KeyId.MouseSideButton1,
MouseButton.XButton2 => KeyId.MouseSideButton2,
_ => KeyId.Unknown,
};
}
}
/// <summary>
/// 用于与VK/Windows.Input.Key解耦,值与VK对应,但是仅包含美式键盘(104键,不包括媒体控制等)和鼠标中的按键
/// </summary>
public enum KeyId
{
/// <summary>无</summary>
None = 0x00,
/// <summary>未知按键</summary>
Unknown = 0xFF,
#region 鼠标按键
/// <summary>鼠标左键</summary>
MouseLeftButton = 0x01,
/// <summary>鼠标右键</summary>
MouseRightButton = 0x02,
/// <summary>鼠标中键(滚轮)</summary>
MouseMiddleButton = 0x04,
/// <summary>鼠标侧键1(后退)</summary>
MouseSideButton1 = 0x05,
/// <summary>鼠标侧键2(前进)</summary>
MouseSideButton2 = 0x06,
#endregion
#region F键区
/// <summary>F1</summary>
F1 = 0x70,
/// <summary>F2</summary>
F2 = 0x71,
/// <summary>F3</summary>
F3 = 0x72,
/// <summary>F4</summary>
F4 = 0x73,
/// <summary>F5</summary>
F5 = 0x74,
/// <summary>F6</summary>
F6 = 0x75,
/// <summary>F7</summary>
F7 = 0x76,
/// <summary>F8</summary>
F8 = 0x77,
/// <summary>F9</summary>
F9 = 0x78,
/// <summary>F10</summary>
F10 = 0x79,
/// <summary>F11</summary>
F11 = 0x7A,
/// <summary>F12</summary>
F12 = 0x7B,
#endregion
#region 控制&功能键
/// <summary>Esc</summary>
Escape = 0x1B,
/// <summary>PrintScreen</summary>
PrintScreen = 0x2C,
/// <summary>ScrollLock</summary>
ScrollLock = 0x91,
/// <summary>Pause</summary>
Pause = 0x13,
/// <summary>Insert</summary>
Insert = 0x2D,
/// <summary>Delete</summary>
Delete = 0x2E,
/// <summary>Home</summary>
Home = 0x24,
/// <summary>End</summary>
End = 0x23,
/// <summary>Page Up</summary>
PageUp = 0x21,
/// <summary>Page Down</summary>
PageDown = 0x22,
/// <summary>Backspace退格</summary>
Backspace = 0x08,
/// <summary>Tab</summary>
Tab = 0x09,
/// <summary>Caps Lock大写锁定</summary>
CapsLock = 0x14,
/// <summary>Enter回车</summary>
Enter = 0x0D,
///// <summary>Shift</summary>
//Shift = 0x10,
/// <summary>左Shift</summary>
LeftShift = 0xA0,
/// <summary>右Shift</summary>
RightShift = 0xA1,
///// <summary>Ctrl</summary>
//Ctrl = 0x11,
/// <summary>左Ctrl</summary>
LeftCtrl = 0xA2,
/// <summary>右Ctrl</summary>
RightCtrl = 0xA3,
///// <summary>Alt</summary>
//Alt = 0x12,
/// <summary>左Alt</summary>
LeftAlt = 0xA4,
/// <summary>右Alt</summary>
RightAlt = 0xA5,
/// <summary>左Win键 (Microsoft Natural Keyboard)</summary>
LeftWin = 0x5B,
/// <summary>右Win键 (Microsoft Natural Keyboard)</summary>
RightWin = 0x5C,
/// <summary>菜单键 (Microsoft Natural Keyboard)</summary>
Apps = 0x5D,
/// <summary>Space空格键</summary>
Space = 0x20,
#endregion
#region 方向键
/// <summary>方向键 ←</summary>
Left = 0x25,
/// <summary>方向键 ↑</summary>
Up = 0x26,
/// <summary>方向键 →</summary>
Right = 0x27,
/// <summary>方向键 ↓</summary>
Down = 0x28,
#endregion
#region 字母区 - 字母
/// <summary>A</summary>
A = 0x41,
/// <summary>B</summary>
B = 0x42,
/// <summary>C</summary>
C = 0x43,
/// <summary>D</summary>
D = 0x44,
/// <summary>E</summary>
E = 0x45,
/// <summary>F</summary>
F = 0x46,
/// <summary>G</summary>
G = 0x47,
/// <summary>H</summary>
H = 0x48,
/// <summary>I</summary>
I = 0x49,
/// <summary>J</summary>
J = 0x4A,
/// <summary>K</summary>
K = 0x4B,
/// <summary>L</summary>
L = 0x4C,
/// <summary>M</summary>
M = 0x4D,
/// <summary>N</summary>
N = 0x4E,
/// <summary>O</summary>
O = 0x4F,
/// <summary>P</summary>
P = 0x50,
/// <summary>Q</summary>
Q = 0x51,
/// <summary>R</summary>
R = 0x52,
/// <summary>S</summary>
S = 0x53,
/// <summary>T</summary>
T = 0x54,
/// <summary>U</summary>
U = 0x55,
/// <summary>V</summary>
V = 0x56,
/// <summary>W</summary>
W = 0x57,
/// <summary>X</summary>
X = 0x58,
/// <summary>Y</summary>
Y = 0x59,
/// <summary>Z</summary>
Z = 0x5A,
#endregion
#region 字母区 - 数字
/// <summary>0</summary>
D0 = 0x30,
/// <summary>1</summary>
D1 = 0x31,
/// <summary>2</summary>
D2 = 0x32,
/// <summary>3</summary>
D3 = 0x33,
/// <summary>4</summary>
D4 = 0x34,
/// <summary>5</summary>
D5 = 0x35,
/// <summary>6</summary>
D6 = 0x36,
/// <summary>7</summary>
D7 = 0x37,
/// <summary>8</summary>
D8 = 0x38,
/// <summary>9</summary>
D9 = 0x39,
#endregion
#region 字母区 - 符号
/// <summary>引号 '</summary>
Apostrophe = 0xDE,
/// <summary>逗号 ,</summary>
Comma = 0xBC,
/// <summary>连接符 -</summary>
Minus = 0xBD,
/// <summary>等于号 =</summary>
Equal = 0xBB,
/// <summary>句号 .</summary>
Period = 0xBE,
/// <summary>斜杠 /</summary>
Slash = 0xBF,
/// <summary>反斜杠 \</summary>
Backslash = 0xE2,
/// <summary>分号 ;</summary>
Semicolon = 0xBA,
/// <summary>左方括号 [</summary>
LeftSquareBracket = 0xDB,
/// <summary>右方括号 ]</summary>
RightSquareBracket = 0xDD,
/// <summary>波浪号 `</summary>
Tilde = 0xC0,
#endregion
#region 小键盘区
/// <summary>Num Lock</summary>
NumLock = 0x90,
/// <summary>Num 0</summary>
NumPad0 = 0x60,
/// <summary>Num 1</summary>
NumPad1 = 0x61,
/// <summary>Num 2</summary>
NumPad2 = 0x62,
/// <summary>Num 3</summary>
NumPad3 = 0x63,
/// <summary>Num 4</summary>
NumPad4 = 0x64,
/// <summary>Num 5</summary>
NumPad5 = 0x65,
/// <summary>Num 6</summary>
NumPad6 = 0x66,
/// <summary>Num 7</summary>
NumPad7 = 0x67,
/// <summary>Num 8</summary>
NumPad8 = 0x68,
/// <summary>Num 9</summary>
NumPad9 = 0x69,
/// <summary>Num .</summary>
Decimal = 0x6E,
/// <summary>Num /</summary>
Divide = 0x6F,
/// <summary>Num *</summary>
Multiply = 0x6A,
/// <summary>Num -</summary>
Subtract = 0x6D,
/// <summary>Num +</summary>
Add = 0x6B,
/// <summary>Num Enter</summary>
NumEnter = 0x0E,
#endregion
}
@@ -34,7 +34,7 @@ public partial class PathingConditionConfig : ObservableObject
new Condition
{
Subject = "队伍中角色",
Object = ["绮良良", "莱依拉", "芭芭拉", "七七"],
Object = ["绮良良", "莱依拉", "茜特菈莉", "芭芭拉", "七七"],
Result = "循环短E"
},
@@ -61,6 +61,14 @@ public partial class PathingPartyConfig : ObservableObject
[ObservableProperty]
private bool _onlyInTeleportRecover = false;
//允许在jsScript脚本中使用此路径追踪配置
[ObservableProperty]
private bool _jsScriptUseEnabled = false;
//允许在此调度器中(一般在JS脚本中)调用自动战斗任务时,采用此追踪配置里的战斗策略
[ObservableProperty]
private bool _soloTaskUseFightEnabled = false;
// 使用小道具的间隔时间
[ObservableProperty]
private int _useGadgetIntervalMs = 0;
@@ -68,10 +76,14 @@ public partial class PathingPartyConfig : ObservableObject
// 启用进入剧情自动脱离
[ObservableProperty]
private bool _autoSkipEnabled = true;
// 自动冲刺启用
[ObservableProperty]
private bool _autoRunEnabled = true;
//启用自动战斗配置
[ObservableProperty]
private bool _autoFightEabled = false;
private bool _autoFightEnabled = false;
[ObservableProperty]
private AutoFightConfig _autoFightConfig = new();
@@ -1,4 +1,5 @@
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Model;
@@ -18,6 +19,10 @@ public class MouseKeyMonitor
/// </summary>
private readonly Timer _fTimer = new();
private Keys _pickUpKey = Keys.F;
private User32.VK _pickUpKeyCode = User32.VK.VK_F;
//private readonly Random _random = new();
/// <summary>
@@ -25,6 +30,10 @@ public class MouseKeyMonitor
/// </summary>
private readonly Timer _spaceTimer = new();
private Keys _releaseControlKey = Keys.Space;
private User32.VK _releaseControlKeyCode = User32.VK.VK_SPACE;
private DateTime _firstFKeyDownTime = DateTime.MaxValue;
/// <summary>
@@ -49,14 +58,19 @@ public class MouseKeyMonitor
_globalHook.MouseWheelExt += GlobalHookMouseWheelExt;
//_globalHook.KeyPress += GlobalHookKeyPress;
_pickUpKey = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToWinFormKeys();
_pickUpKeyCode = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToVK();
_releaseControlKey = TaskContext.Instance().Config.KeyBindingsConfig.Jump.ToWinFormKeys();
_releaseControlKeyCode = TaskContext.Instance().Config.KeyBindingsConfig.Jump.ToVK();
_firstSpaceKeyDownTime = DateTime.MaxValue;
var si = TaskContext.Instance().Config.MacroConfig.SpaceFireInterval;
_spaceTimer.Interval = si;
_spaceTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(User32.VK.VK_SPACE); };
_spaceTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(_releaseControlKeyCode); };
var fi = TaskContext.Instance().Config.MacroConfig.FFireInterval;
_fTimer.Interval = fi;
_fTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(User32.VK.VK_F); };
_fTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(_pickUpKeyCode); };
}
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
@@ -67,7 +81,7 @@ public class MouseKeyMonitor
// 热键按下事件
HotKeyDown(sender, e);
if (e.KeyCode == Keys.Space)
if (e.KeyCode == _releaseControlKey)
{
if (_firstSpaceKeyDownTime == DateTime.MaxValue)
{
@@ -81,7 +95,7 @@ public class MouseKeyMonitor
_spaceTimer.Start();
}
}
else if (e.KeyCode == Keys.F)
else if (e.KeyCode == _pickUpKey)
{
if (_firstFKeyDownTime == DateTime.MaxValue)
{
@@ -105,7 +119,7 @@ public class MouseKeyMonitor
// 热键松开事件
HotKeyUp(sender, e);
if (e.KeyCode == Keys.Space)
if (e.KeyCode == _releaseControlKey)
{
if (_firstSpaceKeyDownTime != DateTime.MaxValue)
{
@@ -115,7 +129,7 @@ public class MouseKeyMonitor
_spaceTimer.Stop();
}
}
else if (e.KeyCode == Keys.F)
else if (e.KeyCode == _pickUpKey)
{
if (_firstFKeyDownTime != DateTime.MaxValue)
{
@@ -7,7 +7,6 @@ using OpenCvSharp.XFeatures2D;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
@@ -137,10 +136,10 @@ public class FeatureMatcher
/// <summary>
/// 合并邻近的特征点后匹配(临近特征)
/// </summary>
/// <param name="queryMat">查询的图</param>
/// <param name="queryMat">查询图像的 Mat 对象。</param>
/// <param name="prevX">上次匹配到的坐标x</param>
/// <param name="prevY">上次匹配到的坐标y</param>
/// <param name="queryMatMask">查询Mask</param>
/// <param name="queryMatMask">查询图像的 Mask,用于限定检测特征的区域。</param>
/// <returns></returns>
public Point2f Match(Mat queryMat, float prevX, float prevY, Mat? queryMatMask = null)
{
@@ -151,18 +150,17 @@ public class FeatureMatcher
Debug.WriteLine($"---------切换到新的特征块({cellRow},{cellCol}),合并特征点--------");
_lastMergedBlock = KeyPointFeatureBlockHelper.MergeNeighboringFeatures(_blocks, _trainDescriptors, cellRow, cellCol);
}
return Match(_lastMergedBlock.KeyPointArray, _lastMergedBlock.Descriptor!, queryMat, queryMatMask);
}
/// <summary>
/// 普通匹配
/// 用于从训练图像和查询图像中找到匹配的特征点,计算透视变换并确定查询图像的中心点在训练图像中的位置。
/// </summary>
/// <param name="trainKeyPoints"></param>
/// <param name="trainDescriptors"></param>
/// <param name="queryMat"></param>
/// <param name="queryMatMask"></param>
/// <param name="matcherType"></param>
/// <param name="trainKeyPoints">训练图像中的关键点集合。</param>
/// <param name="trainDescriptors">训练图像的特征描述子。</param>
/// <param name="queryMat">查询图像的 Mat 对象。</param>
/// <param name="queryMatMask">查询图像的 Mask,用于限定检测特征的区域。</param>
/// <param name="matcherType">描述符匹配器的类型,默认为 DescriptorMatcherType.FlannBased</param>
/// <returns></returns>
public Point2f Match(KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
@@ -8,7 +8,6 @@ namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
public class FeatureStorage(string name)
{
private readonly string rootPath = Global.Absolute(@"Assets\Map\");
public void SetType(Feature2DType type)
{
TypeName = type.ToString();
@@ -16,24 +15,6 @@ public class FeatureStorage(string name)
public string TypeName { get; set; } = "UNKNOWN";
// public KeyPoint[]? LoadKeyPointArray1()
// {
// CreateFolder();
// string kpPath = Path.Combine(rootPath, $"{name}_{TypeName}.kp");
// if (File.Exists(kpPath))
// {
// return ObjectUtils.Deserialize(File.ReadAllBytes(kpPath)) as KeyPoint[];
// }
// return null;
// }
//
// public void SaveKeyPointArray1(KeyPoint[] kpArray)
// {
// CreateFolder();
// string kpPath = Path.Combine(rootPath, $"{name}_{TypeName}.kp");
// File.WriteAllBytes(kpPath, ObjectUtils.Serialize(kpArray));
// }
public KeyPoint[]? LoadKeyPointArray()
{
CreateFolder();
@@ -65,32 +46,6 @@ public class FeatureStorage(string name)
}
}
// public Mat? LoadDescMat1()
// {
// CreateFolder();
// // 格式: Surf_336767x128.mat
// var files = Directory.GetFiles(rootPath, $"{name}_{TypeName}_*.mat", SearchOption.AllDirectories);
// if (files.Length == 0)
// {
// return null;
// }
// else if (files.Length > 1)
// {
// Debug.WriteLine($"[FeatureSerializer] Found multiple files: {string.Join(", ", files)}");
// }
// var rowColPair = Path.GetFileNameWithoutExtension(files[0])
// .Replace($"{name}_{TypeName}_", "")
// .Split('x');
// if (rowColPair.Length != 2)
// {
// Debug.WriteLine($"[FeatureSerializer] Invalid file name: {files[0]}");
// return null;
// }
// GCHandle pinnedArray = GCHandle.Alloc(ObjectUtils.Deserialize(File.ReadAllBytes(files[0])), GCHandleType.Pinned);
// IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// return new Mat(Convert.ToInt32(rowColPair[0]), Convert.ToInt32(rowColPair[1]), MatType.CV_32FC1, pointer);
// }
public Mat? LoadDescMat()
{
CreateFolder();
@@ -109,22 +64,6 @@ public class FeatureStorage(string name)
return mat;
}
// public void SaveDescMat1(Mat descMat)
// {
// CreateFolder();
// // 删除旧文件
// var files = Directory.GetFiles(rootPath, $"{name}_{TypeName}_*.mat", SearchOption.AllDirectories);
// foreach (var file in files)
// {
// File.Delete(file);
// }
//
// var descPath = Path.Combine(rootPath, $"{name}_{TypeName}_{descMat.Rows}x{descMat.Cols}.mat");
// var bytes = new byte[descMat.Step(0) * descMat.Rows]; // matSrcRet.Total() * matSrcRet.ElemSize()
// Marshal.Copy(descMat.Data, bytes, 0, bytes.Length);
// File.WriteAllBytes(descPath, ObjectUtils.Serialize(bytes));
// }
public void SaveDescMat(Mat descMat)
{
CreateFolder();
@@ -135,7 +74,6 @@ public class FeatureStorage(string name)
{
File.Delete(file);
}
var descPath = Path.Combine(rootPath, fileName);
FileStorage fs = new(descPath, FileStorage.Modes.Write);
fs.Write("desc", descMat);
@@ -5,17 +5,29 @@ using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class AutoPathingScript(string rootPath)
public class AutoPathingScript
{
private object? _config = null;
private string _rootPath;
public AutoPathingScript(string rootPath, object? config) {
_config = config;
_rootPath = rootPath;
}
public async Task Run(string json)
{
var task = PathingTask.BuildFromJson(json);
await new PathExecutor(CancellationContext.Instance.Cts.Token).Pathing(task);
var pathExecutor = new PathExecutor(CancellationContext.Instance.Cts.Token);
if (_config != null && _config is PathingPartyConfig patyConfig ) {
pathExecutor.PartyConfig = patyConfig;
}
await pathExecutor.Pathing(task);
}
public async Task RunFile(string path)
{
var json = await new LimitedFile(rootPath).ReadText(path);
var json = await new LimitedFile(_rootPath).ReadText(path);
await Run(json);
}
@@ -8,11 +8,17 @@ using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoWood;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Dispatcher
{
private object _config=null;
public Dispatcher(object config)
{
_config = config;
}
public void RunTask()
{
}
@@ -77,13 +83,15 @@ public class Dispatcher
break;
case "AutoFight":
if (taskSettingsPageViewModel.GetFightStrategy(out var path1))
/*if (taskSettingsPageViewModel.GetFightStrategy(out var path1))
{
return;
}
var autoFightConfig = TaskContext.Instance().Config.AutoFightConfig;
var param = new AutoFightParam(path1, autoFightConfig);
await new AutoFightTask(param).Start(CancellationContext.Instance.Cts.Token);
await new AutoFightTask(param).Start(CancellationContext.Instance.Cts.Token);*/
await new AutoFightHandler().RunAsyncByScript(CancellationContext.Instance.Cts.Token, null,_config);
break;
case "AutoDomain":
@@ -6,6 +6,7 @@ using System.Threading.Tasks;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script;
@@ -17,19 +18,19 @@ public class EngineExtend
/// <param name="engine"></param>
/// <param name="workDir"></param>
/// <param name="searchPaths"></param>
public static void InitHost(IScriptEngine engine, string workDir, string[]? searchPaths = null)
public static void InitHost(IScriptEngine engine, string workDir, string[]? searchPaths = null, object? config = null)
{
// engine.AddHostObject("xHost", new ExtendedHostFunctions()); // 有越权的安全风险
// 添加我的自定义实例化对象
engine.AddHostObject("keyMouseScript", new KeyMouseScript(workDir));
engine.AddHostObject("pathingScript", new AutoPathingScript(workDir));
engine.AddHostObject("pathingScript", new AutoPathingScript(workDir, config));
engine.AddHostObject("genshin", new Dependence.Genshin());
engine.AddHostObject("log", new Log());
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
// 任务调度器
engine.AddHostObject("dispatcher", new Dispatcher());
engine.AddHostObject("dispatcher", new Dispatcher(config));
engine.AddHostType("RealtimeTimer", typeof(RealtimeTimer));
engine.AddHostType("SoloTask", typeof(SoloTask));
@@ -138,7 +138,14 @@ public partial class ScriptGroupProject : ObservableObject
throw new Exception("JS脚本未初始化");
}
JsScriptSettingsObject ??= new ExpandoObject();
await Project.ExecuteAsync(JsScriptSettingsObject);
var pathingPartyConfig = GroupInfo?.Config.PathingConfig;
if (!(pathingPartyConfig is {Enabled:true,JsScriptUseEnabled:true}))
{
pathingPartyConfig = null;
}
await Project.ExecuteAsync(JsScriptSettingsObject,pathingPartyConfig);
}
if (Type == "KeyMouse")
{
@@ -57,20 +57,20 @@ public class ScriptProject
return stackPanel;
}
public IScriptEngine BuildScriptEngine()
public IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig = null)
{
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library);
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library,partyConfig);
return engine;
}
public async Task ExecuteAsync(dynamic? context = null)
public async Task ExecuteAsync(dynamic? context = null, PathingPartyConfig? partyConfig=null)
{
// 默认值
GlobalMethod.SetGameMetrics(1920, 1080);
// 加载代码
var code = await LoadCode();
var engine = BuildScriptEngine();
var engine = BuildScriptEngine(partyConfig);
if (context != null)
{
// 写入配置的内容
@@ -391,6 +391,9 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
}
else if (File.Exists(scriptPath))
{
// 目标文件所在文件夹不存在时创建它
Directory.CreateDirectory(Path.GetDirectoryName(destPath)!);
if (File.Exists(destPath))
{
File.Delete(destPath);
@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BetterGenshinImpact.Core.Simulator.Extensions;
/// <summary>
/// 模拟按键类型
/// </summary>
public enum KeyType
{
/// <summary>
/// 单击按键(KeyPress)
/// </summary>
KeyPress,
/// <summary>
/// 按住按键(KeyDown)
/// </summary>
KeyDown,
/// <summary>
/// 释放按键(KeyUp)
/// </summary>
KeyUp,
/// <summary>
/// 长按1s
/// </summary>
Hold,
}
/// <summary>
/// 原神按键动作
/// </summary>
public enum GIActions
{
/// <summary>
/// 向前移动
/// </summary>
MoveForward,
/// <summary>
/// 向后移动
/// </summary>
MoveBackward,
/// <summary>
/// 向左移动
/// </summary>
MoveLeft,
/// <summary>
/// 向右移动
/// </summary>
MoveRight,
/// <summary>
/// 切换走/跑;特定操作模式下向下移动
/// </summary>
SwitchToWalkOrRun,
/// <summary>
/// 普通攻击
/// </summary>
NormalAttack,
/// <summary>
/// 元素战技
/// </summary>
ElementalSkill,
/// <summary>
/// 元素爆发
/// </summary>
ElementalBurst,
/// <summary>
/// 冲刺(键盘)
/// </summary>
SprintKeyboard,
/// <summary>
/// 冲刺(鼠标)
/// </summary>
SprintMouse,
/// <summary>
/// 切换瞄准模式
/// </summary>
SwitchAimingMode,
/// <summary>
/// 跳跃;特定操作模式下向上移动
/// </summary>
Jump,
/// <summary>
/// 落下
/// </summary>
Drop,
/// <summary>
/// 拾取/交互(自动拾取由AutoPick模块管理)
/// </summary>
PickUpOrInteract,
/// <summary>
/// 快捷使用小道具
/// </summary>
QuickUseGadget,
/// <summary>
/// 特定玩法内交互操作
/// </summary>
InteractionInSomeMode,
/// <summary>
/// 开启任务追踪
/// </summary>
QuestNavigation,
/// <summary>
/// 中断挑战
/// </summary>
AbandonChallenge,
/// <summary>
/// 切换小队角色1
/// </summary>
SwitchMember1,
/// <summary>
/// 切换小队角色2
/// </summary>
SwitchMember2,
/// <summary>
/// 切换小队角色3
/// </summary>
SwitchMember3,
/// <summary>
/// 切换小队角色4
/// </summary>
SwitchMember4,
/// <summary>
/// 切换小队角色5
/// </summary>
SwitchMember5,
/// <summary>
/// 呼出快捷轮盘
/// </summary>
ShortcutWheel,
/// <summary>
/// 打开背包
/// </summary>
OpenInventory,
/// <summary>
/// 打开角色界面
/// </summary>
OpenCharacterScreen,
/// <summary>
/// 打开地图
/// </summary>
OpenMap,
/// <summary>
/// 打开派蒙界面
/// </summary>
OpenPaimonMenu,
/// <summary>
/// 打开冒险之证界面
/// </summary>
OpenAdventurerHandbook,
/// <summary>
/// 打开多人游戏界面
/// </summary>
OpenCoOpScreen,
/// <summary>
/// 打开祈愿界面
/// </summary>
OpenWishScreen,
/// <summary>
/// 打开纪行界面
/// </summary>
OpenBattlePassScreen,
/// <summary>
/// 打开活动面板
/// </summary>
OpenTheEventsMenu,
/// <summary>
/// 打开玩法系统界面(尘歌壶内猫尾酒馆内)
/// </summary>
OpenTheSettingsMenu,
/// <summary>
/// 打开摆设界面(尘歌壶内)
/// </summary>
OpenTheFurnishingScreen,
/// <summary>
/// 打开星之归还(条件符合期间生效)
/// </summary>
OpenStellarReunion,
/// <summary>
/// 开关任务菜单
/// </summary>
OpenQuestMenu,
/// <summary>
/// 打开通知详情
/// </summary>
OpenNotificationDetails,
/// <summary>
/// 打开聊天界面
/// </summary>
OpenChatScreen,
/// <summary>
/// 打开特殊环境说明
/// </summary>
OpenSpecialEnvironmentInformation,
/// <summary>
/// 查看教程详情
/// </summary>
CheckTutorialDetails,
/// <summary>
/// 长按打开元素视野
/// </summary>
ElementalSight,
/// <summary>
/// 呼出鼠标
/// </summary>
ShowCursor,
/// <summary>
/// 打开队伍配置界面
/// </summary>
OpenPartySetupScreen,
/// <summary>
/// 打开好友界面
/// </summary>
OpenFriendsScreen,
/// <summary>
/// 隐藏主界面
/// </summary>
HideUI,
}
@@ -0,0 +1,135 @@
using BetterGenshinImpact.Core.Config;
using System;
using System.Collections.Generic;
using System.Text;
using BetterGenshinImpact.Core.Simulator;
using System.Threading;
using Fischless.WindowsInput;
namespace BetterGenshinImpact.Core.Simulator.Extensions;
/// <summary>
/// 用于扩展<seealso cref="Fischless.WindowsInput.InputSimulator"/>的功能
/// </summary>
public static class InputSimulatorExtension
{
/// <summary>
/// 模拟玩家操作
/// </summary>
/// <param name="action">动作</param>
/// <param name="type">按键类型</param>
public static void SimulateAction(this InputSimulator self, GIActions action, KeyType type = KeyType.KeyPress)
{
var key = action.ToActionKey();
switch (type)
{
case KeyType.KeyPress:
KeyPress(self, key);
break;
case KeyType.KeyDown:
KeyDown(self, key);
break;
case KeyType.KeyUp:
KeyUp(self, key);
break;
case KeyType.Hold:
HoldKeyPress(self, key);
break;
default:
break;
}
}
private static void HoldKeyPress(InputSimulator self, KeyId key)
{
KeyDown(self, key);
Thread.Sleep(1000);
KeyUp(self, key);
}
private static void KeyPress(InputSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
self.Mouse.LeftButtonClick();
break;
case KeyId.MouseRightButton:
self.Mouse.RightButtonClick();
break;
case KeyId.MouseMiddleButton:
self.Mouse.MiddleButtonClick();
break;
case KeyId.MouseSideButton1:
self.Mouse.XButtonClick(0x0001);
break;
case KeyId.MouseSideButton2:
self.Mouse.XButtonClick(0x0001);
break;
default:
self.Keyboard.KeyPress(key.ToVK());
break;
}
}
private static void KeyDown(InputSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
self.Mouse.LeftButtonDown();
break;
case KeyId.MouseRightButton:
self.Mouse.RightButtonDown();
break;
case KeyId.MouseMiddleButton:
self.Mouse.MiddleButtonDown();
break;
case KeyId.MouseSideButton1:
self.Mouse.XButtonDown(0x0001);
break;
case KeyId.MouseSideButton2:
self.Mouse.XButtonDown(0x0001);
break;
default:
self.Keyboard.KeyDown(key.ToVK());
break;
}
}
private static void KeyUp(InputSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
self.Mouse.LeftButtonUp();
break;
case KeyId.MouseRightButton:
self.Mouse.RightButtonUp();
break;
case KeyId.MouseMiddleButton:
self.Mouse.MiddleButtonUp();
break;
case KeyId.MouseSideButton1:
self.Mouse.XButtonUp(0x0001);
break;
case KeyId.MouseSideButton2:
self.Mouse.XButtonUp(0x0001);
break;
default:
self.Keyboard.KeyUp(key.ToVK());
break;
}
}
}
@@ -0,0 +1,204 @@
using BetterGenshinImpact.Core.Config;
using Fischless.WindowsInput;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace BetterGenshinImpact.Core.Simulator.Extensions;
/// <summary>
/// 为<seealso cref="PostMessageSimulator"/>提供扩展功能
/// </summary>
public static class PostMessageSimulatorExtension
{
/// <summary>
/// 模拟玩家操作
/// </summary>
/// <param name="action">动作</param>
/// <param name="type">按键类型</param>
public static PostMessageSimulator SimulateAction(this PostMessageSimulator self, GIActions action, KeyType type = KeyType.KeyPress)
{
var key = action.ToActionKey();
switch (type)
{
case KeyType.KeyPress:
KeyPress(self, key);
break;
case KeyType.KeyDown:
KeyDown(self, key);
break;
case KeyType.KeyUp:
KeyUp(self, key);
break;
case KeyType.Hold:
HoldKeyPress(self, key);
break;
default:
break;
}
return self;
}
private static void HoldKeyPress(PostMessageSimulator self, KeyId key)
{
self.LongKeyPress(key.ToVK());
}
private static void KeyPress(PostMessageSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
self.LeftButtonClick();
break;
case KeyId.MouseRightButton:
self.RightButtonClick();
break;
case KeyId.MouseMiddleButton:
case KeyId.MouseSideButton1:
case KeyId.MouseSideButton2:
break;
default:
self.KeyPress(key.ToVK());
break;
}
}
private static void KeyDown(PostMessageSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
self.LeftButtonDown();
break;
case KeyId.MouseRightButton:
self.RightButtonDown();
break;
case KeyId.MouseMiddleButton:
case KeyId.MouseSideButton1:
case KeyId.MouseSideButton2:
break;
default:
self.KeyDown(key.ToVK());
break;
}
}
private static void KeyUp(PostMessageSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
self.LeftButtonUp();
break;
case KeyId.MouseRightButton:
self.RightButtonUp();
break;
case KeyId.MouseMiddleButton:
case KeyId.MouseSideButton1:
case KeyId.MouseSideButton2:
break;
default:
self.KeyUp(key.ToVK());
break;
}
}
/// <summary>
/// 模拟玩家操作(后台)
/// </summary>
/// <param name="action">动作</param>
/// <param name="type">按键类型</param>
public static PostMessageSimulator SimulateActionBackground(this PostMessageSimulator self, GIActions action, KeyType type = KeyType.KeyPress)
{
var key = action.ToActionKey();
switch (type)
{
case KeyType.KeyPress:
KeyPressBackground(self, key);
break;
case KeyType.KeyDown:
KeyDownBackground(self, key);
break;
case KeyType.KeyUp:
KeyUpBackground(self, key);
break;
case KeyType.Hold:
break;
default:
break;
}
return self;
}
private static void KeyPressBackground(PostMessageSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
self.LeftButtonClickBackground();
break;
case KeyId.MouseRightButton:
case KeyId.MouseMiddleButton:
case KeyId.MouseSideButton1:
case KeyId.MouseSideButton2:
break;
default:
self.KeyPressBackground(key.ToVK());
break;
}
}
private static void KeyDownBackground(PostMessageSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
case KeyId.MouseRightButton:
case KeyId.MouseMiddleButton:
case KeyId.MouseSideButton1:
case KeyId.MouseSideButton2:
break;
default:
self.KeyDownBackground(key.ToVK());
break;
}
}
private static void KeyUpBackground(PostMessageSimulator self, KeyId key)
{
switch (key)
{
case KeyId.None:
case KeyId.Unknown:
break;
case KeyId.MouseLeftButton:
case KeyId.MouseRightButton:
case KeyId.MouseMiddleButton:
case KeyId.MouseSideButton1:
case KeyId.MouseSideButton2:
break;
default:
self.KeyUpBackground(key.ToVK());
break;
}
}
}
@@ -0,0 +1,79 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace BetterGenshinImpact.Core.Simulator.Extensions;
public static class SimulateKeyHelper
{
private static KeyBindingsConfig KeyConfig => TaskContext.Instance().Config.KeyBindingsConfig;
public static KeyId ToActionKey(this GIActions action)
{
return GetActionKey(action);
}
/// <summary>
/// 通过ActionId取得实际的键盘绑定
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
public static KeyId GetActionKey(GIActions action)
{
return action switch
{
GIActions.MoveForward => KeyConfig.MoveForward,
GIActions.MoveBackward => KeyConfig.MoveBackward,
GIActions.MoveLeft => KeyConfig.MoveLeft,
GIActions.MoveRight => KeyConfig.MoveRight,
GIActions.SwitchToWalkOrRun => KeyConfig.SwitchToWalkOrRun,
GIActions.NormalAttack => KeyConfig.NormalAttack,
GIActions.ElementalSkill => KeyConfig.ElementalSkill,
GIActions.ElementalBurst => KeyConfig.ElementalBurst,
GIActions.SprintKeyboard => KeyConfig.SprintKeyboard,
GIActions.SprintMouse => KeyConfig.SprintMouse,
GIActions.SwitchAimingMode => KeyConfig.SwitchAimingMode,
GIActions.Jump => KeyConfig.Jump,
GIActions.Drop => KeyConfig.Drop,
GIActions.PickUpOrInteract => KeyConfig.PickUpOrInteract,
GIActions.QuickUseGadget => KeyConfig.QuickUseGadget,
GIActions.InteractionInSomeMode => KeyConfig.InteractionInSomeMode,
GIActions.QuestNavigation => KeyConfig.QuestNavigation,
GIActions.AbandonChallenge => KeyConfig.AbandonChallenge,
GIActions.SwitchMember1 => KeyConfig.SwitchMember1,
GIActions.SwitchMember2 => KeyConfig.SwitchMember2,
GIActions.SwitchMember3 => KeyConfig.SwitchMember3,
GIActions.SwitchMember4 => KeyConfig.SwitchMember4,
GIActions.SwitchMember5 => KeyConfig.SwitchMember5,
GIActions.ShortcutWheel => KeyConfig.ShortcutWheel,
GIActions.OpenInventory => KeyConfig.OpenInventory,
GIActions.OpenCharacterScreen => KeyConfig.OpenCharacterScreen,
GIActions.OpenMap => KeyConfig.OpenMap,
GIActions.OpenPaimonMenu => KeyConfig.OpenPaimonMenu,
GIActions.OpenAdventurerHandbook => KeyConfig.OpenAdventurerHandbook,
GIActions.OpenCoOpScreen => KeyConfig.OpenCoOpScreen,
GIActions.OpenWishScreen => KeyConfig.OpenWishScreen,
GIActions.OpenBattlePassScreen => KeyConfig.OpenBattlePassScreen,
GIActions.OpenTheEventsMenu => KeyConfig.OpenTheEventsMenu,
GIActions.OpenTheSettingsMenu => KeyConfig.OpenTheSettingsMenu,
GIActions.OpenTheFurnishingScreen => KeyConfig.OpenTheFurnishingScreen,
GIActions.OpenStellarReunion => KeyConfig.OpenStellarReunion,
GIActions.OpenQuestMenu => KeyConfig.OpenQuestMenu,
GIActions.OpenNotificationDetails => KeyConfig.OpenNotificationDetails,
GIActions.OpenChatScreen => KeyConfig.OpenChatScreen,
GIActions.OpenSpecialEnvironmentInformation => KeyConfig.OpenSpecialEnvironmentInformation,
GIActions.CheckTutorialDetails => KeyConfig.CheckTutorialDetails,
GIActions.ElementalSight => KeyConfig.ElementalSight,
GIActions.ShowCursor => KeyConfig.ShowCursor,
GIActions.OpenPartySetupScreen => KeyConfig.OpenPartySetupScreen,
GIActions.OpenFriendsScreen => KeyConfig.OpenFriendsScreen,
GIActions.HideUI => KeyConfig.HideUI,
_ => default,
};
}
}
@@ -2,6 +2,7 @@
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.AutoFight.Model;
@@ -55,7 +56,8 @@ public class AutoDomainTask : ISoloTask
public AutoDomainTask(AutoDomainParam taskParam)
{
_taskParam = taskParam;
_simulator = AutoFightContext.Instance.Simulator;
AutoFightAssets.DestroyInstance();
_simulator = TaskContext.Instance().PostMessageSimulator;
_predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute(@"Assets\Model\Domain\bgi_tree.onnx"))
@@ -70,8 +72,7 @@ public class AutoDomainTask : ISoloTask
public async Task Start(CancellationToken ct)
{
_ct = ct;
AutoFightAssets.DestroyInstance();
Init();
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Started().Build()); // TODO: 通知后续需要删除迁移
@@ -188,6 +189,7 @@ public class AutoDomainTask : ISoloTask
if (gameScreenSize.Width * 9 != gameScreenSize.Height * 16)
{
Logger.LogError("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏无法正常使用自动秘境功能 !", gameScreenSize.Width, gameScreenSize.Height);
throw new Exception("游戏窗口分辨率不是 16:9");
}
if (gameScreenSize.Width < 1920 || gameScreenSize.Height < 1080)
@@ -223,33 +225,39 @@ public class AutoDomainTask : ISoloTask
if ("芬德尼尔之顶".Equals(_taskParam.DomainName))
{
Simulation.SendInput.Keyboard.KeyDown(VK.VK_S);
Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyDown);
Thread.Sleep(3000);
Simulation.SendInput.Keyboard.KeyUp(VK.VK_S);
Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyUp);
}
else if ("无妄引咎密宫".Equals(_taskParam.DomainName))
{
Simulation.SendInput.Keyboard.KeyDown(VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Thread.Sleep(500);
Simulation.SendInput.Keyboard.KeyUp(VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
Thread.Sleep(100);
Simulation.SendInput.Keyboard.KeyDown(VK.VK_A);
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyDown);
Thread.Sleep(1600);
Simulation.SendInput.Keyboard.KeyUp(VK.VK_A);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
}
else if ("苍白的遗荣".Equals(_taskParam.DomainName))
{
Simulation.SendInput.Keyboard.KeyDown(VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Thread.Sleep(1000);
Simulation.SendInput.Keyboard.KeyUp(VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
}
else if ("太山府".Equals(_taskParam.DomainName))
{
// 直接F即可
// nothing to do
}
else
{
Simulation.SendInput.Keyboard.KeyDown(VK.VK_W);
Thread.Sleep(3000);
Simulation.SendInput.Keyboard.KeyUp(VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Thread.Sleep(2000);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
}
Simulation.SendInput.SimulateAction(GIActions.Drop, KeyType.KeyUp); // 可能爬上去了,X键下来
await Delay(3000, _ct); // 站稳
}
else
@@ -282,15 +290,23 @@ public class AutoDomainTask : ISoloTask
var fightAssets = AutoFightContext.Instance.FightAssets;
// 进入秘境
using var fRectArea = CaptureToRectArea().Find(AutoPickAssets.Instance.FRo);
if (!fRectArea.IsEmpty())
for (int i = 0; i < 3; i++) // 3次重试 有时候会拾取晶蝶
{
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
Logger.LogInformation("自动秘境:{Text}", "进入秘境");
// 秘境开门动画 5s
await Delay(5000, _ct);
using var fRectArea = CaptureToRectArea().Find(AutoPickAssets.Instance.PickRo);
if (!fRectArea.IsEmpty())
{
Simulation.SendInput.Keyboard.KeyPress(AutoPickAssets.Instance.PickVk);
Logger.LogInformation("自动秘境:{Text}", "进入秘境");
// 秘境开门动画 5s
await Delay(5000, _ct);
}
else
{
await Delay(800, _ct);
}
}
int retryTimes = 0, clickCount = 0;
while (retryTimes < 20 && clickCount < 2)
{
@@ -328,7 +344,7 @@ public class AutoDomainTask : ISoloTask
await Delay(1000, _ct);
}
await Delay(1500, _ct);
await Delay(2000, _ct);
}
private List<CombatCommand> FindCombatScriptAndSwitchAvatar(CombatScenes combatScenes)
@@ -352,19 +368,19 @@ public class AutoDomainTask : ISoloTask
await Task.Run((Action)(() =>
{
_simulator.KeyDown(VK.VK_W);
Sleep(20);
_simulator.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Sleep(30, _ct);
// 组合键好像不能直接用 postmessage
if (!_config.WalkToF)
{
Simulation.SendInput.Keyboard.KeyDown(VK.VK_SHIFT);
Simulation.SendInput.SimulateAction(GIActions.SprintKeyboard, KeyType.KeyDown);
}
try
{
while (!_ct.IsCancellationRequested)
{
using var fRectArea = Common.TaskControl.CaptureToRectArea().Find(AutoPickAssets.Instance.FRo);
using var fRectArea = Common.TaskControl.CaptureToRectArea().Find(AutoPickAssets.Instance.PickRo);
if (fRectArea.IsEmpty())
{
Sleep(100, _ct);
@@ -372,18 +388,18 @@ public class AutoDomainTask : ISoloTask
else
{
Logger.LogInformation("检测到交互键");
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
Simulation.SendInput.Keyboard.KeyPress(AutoPickAssets.Instance.PickVk);
break;
}
}
}
finally
{
_simulator.KeyUp(VK.VK_W);
_simulator.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
Sleep(50);
if (!_config.WalkToF)
{
Simulation.SendInput.Keyboard.KeyUp(VK.VK_SHIFT);
Simulation.SendInput.SimulateAction(GIActions.SprintKeyboard, KeyType.KeyUp);
}
}
}), _ct);
@@ -519,7 +535,7 @@ public class AutoDomainTask : ISoloTask
if (Bv.CurrentAvatarIsLowHp(CaptureToRectArea()))
{
// 模拟按键 "Z"
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_Z);
Simulation.SendInput.SimulateAction(GIActions.QuickUseGadget);
Logger.LogInformation("检测到红血,按Z吃药");
// TODO 吃饱了会一直吃
}
@@ -569,12 +585,16 @@ public class AutoDomainTask : ISoloTask
{
return new Task(() =>
{
var keyConfig = TaskContext.Instance().Config.KeyBindingsConfig;
var moveLeftKey = keyConfig.MoveLeft.ToVK();
var moveRightKey = keyConfig.MoveRight.ToVK();
var moveForwardKey = keyConfig.MoveForward.ToVK();
var captureArea = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
var middleX = captureArea.Width / 2;
var leftKeyDown = false;
var rightKeyDown = false;
var noDetectCount = 0;
var prevKey = VK.VK_A;
var prevKey = moveLeftKey;
var backwardsAndForwardsCount = 0;
while (!_ct.IsCancellationRequested)
{
@@ -590,13 +610,13 @@ public class AutoDomainTask : ISoloTask
if (rightKeyDown)
{
// 先松开D键
_simulator.KeyUp(VK.VK_D);
_simulator.KeyUp(moveRightKey);
rightKeyDown = false;
}
if (!leftKeyDown)
{
_simulator.KeyDown(VK.VK_A);
_simulator.KeyDown(moveLeftKey);
leftKeyDown = true;
}
}
@@ -608,13 +628,13 @@ public class AutoDomainTask : ISoloTask
if (leftKeyDown)
{
// 先松开A键
_simulator.KeyUp(VK.VK_A);
_simulator.KeyUp(moveLeftKey);
leftKeyDown = false;
}
if (!rightKeyDown)
{
_simulator.KeyDown(VK.VK_D);
_simulator.KeyDown(moveRightKey);
rightKeyDown = true;
}
}
@@ -623,42 +643,42 @@ public class AutoDomainTask : ISoloTask
// 树在中间 松开所有键
if (rightKeyDown)
{
_simulator.KeyUp(VK.VK_D);
prevKey = VK.VK_D;
_simulator.KeyUp(moveRightKey);
prevKey = moveRightKey;
rightKeyDown = false;
}
if (leftKeyDown)
{
_simulator.KeyUp(VK.VK_A);
prevKey = VK.VK_A;
_simulator.KeyUp(moveLeftKey);
prevKey = moveLeftKey;
leftKeyDown = false;
}
// 松开按键后使用小碎步移动
if (treeMiddleX < middleX)
{
if (prevKey == VK.VK_D)
if (prevKey == moveRightKey)
{
backwardsAndForwardsCount++;
}
_simulator.KeyPress(VK.VK_A, 60);
prevKey = VK.VK_A;
_simulator.KeyPress(moveLeftKey, 60);
prevKey = moveLeftKey;
}
else if (treeMiddleX > middleX)
{
if (prevKey == VK.VK_A)
if (prevKey == moveLeftKey)
{
backwardsAndForwardsCount++;
}
_simulator.KeyPress(VK.VK_D, 60);
prevKey = VK.VK_D;
_simulator.KeyPress(moveRightKey, 60);
prevKey = moveRightKey;
}
else
{
_simulator.KeyPress(VK.VK_W, 60);
_simulator.KeyPress(moveForwardKey, 60);
Sleep(500, _ct);
treeCts.Cancel();
break;
@@ -674,13 +694,13 @@ public class AutoDomainTask : ISoloTask
{
if (leftKeyDown)
{
_simulator.KeyUp(VK.VK_A);
_simulator.KeyUp(moveLeftKey);
leftKeyDown = false;
}
if (!rightKeyDown)
{
_simulator.KeyDown(VK.VK_D);
_simulator.KeyDown(moveRightKey);
rightKeyDown = true;
}
}
@@ -688,13 +708,13 @@ public class AutoDomainTask : ISoloTask
{
if (rightKeyDown)
{
_simulator.KeyUp(VK.VK_D);
_simulator.KeyUp(moveRightKey);
rightKeyDown = false;
}
if (!leftKeyDown)
{
_simulator.KeyDown(VK.VK_A);
_simulator.KeyDown(moveLeftKey);
leftKeyDown = true;
}
}
@@ -703,7 +723,7 @@ public class AutoDomainTask : ISoloTask
if (backwardsAndForwardsCount >= _config.LeftRightMoveTimes)
{
// 左右移动5次说明已经在树中心了
_simulator.KeyPress(VK.VK_W, 60);
_simulator.KeyPress(moveForwardKey, 60);
Sleep(500, _ct);
treeCts.Cancel();
break;
@@ -72,6 +72,40 @@ public partial class AutoFightConfig : ObservableObject
[ObservableProperty]
private bool _pickDropsAfterFightEnabled = true;
[Serializable]
public partial class PickDropsAfterFightConfig : ObservableObject
{
/// <summary>
/// 前进次数
/// </summary>
[ObservableProperty]
private int _forwardTimes = 6;
/// <summary>
/// 校准次数
/// </summary>
[ObservableProperty]
private int _calibrationTimes = 15;
/// <summary>
/// 衰减因子
/// </summary>
[ObservableProperty]
private double _decayFactor = 0.7;
/// <summary>
/// 前进量(秒),设置为0时在[1,3]中随机
/// </summary>
[ObservableProperty]
private int _forwardSeconds = 2;
}
/// <summary>
/// 掉落寻物相关配置
/// </summary>
[ObservableProperty]
private PickDropsAfterFightConfig _pickDropsConfig = new();
/// <summary>
/// 战斗结束后,如果存在枫原万叶,则使用该角色捡材料
/// </summary>
@@ -12,7 +12,7 @@ public class AutoFightContext : Singleton<AutoFightContext>
{
private AutoFightContext()
{
Simulator = Simulation.PostMessage(TaskContext.Instance().GameHandle);
Simulator = TaskContext.Instance().PostMessageSimulator;
}
/// <summary>
@@ -1,5 +1,6 @@
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.Model.Area;
@@ -18,6 +19,9 @@ using BetterGenshinImpact.GameTask.Common.Job;
using OpenCvSharp;
using Vanara;
using Vanara.PInvoke;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.Helpers;
namespace BetterGenshinImpact.GameTask.AutoFight;
@@ -40,22 +44,24 @@ public class AutoFightTask : ISoloTask
private class TaskFightFinishDetectConfig
{
public int DelayTime=1500;
public int DelayTime = 1500;
public Dictionary<string, int> DelayTimes = new();
public double CheckTime = 5;
public List<string> CheckNames = new();
public bool FastCheckEnabled;
public TaskFightFinishDetectConfig(AutoFightParam.FightFinishDetectConfig finishDetectConfig)
{
FastCheckEnabled=finishDetectConfig.FastCheckEnabled;
ParseCheckTimeString(finishDetectConfig.FastCheckParams,out CheckTime,CheckNames);
ParseFastCheckEndDelayString(finishDetectConfig.CheckEndDelay,out DelayTime,DelayTimes);
FastCheckEnabled = finishDetectConfig.FastCheckEnabled;
ParseCheckTimeString(finishDetectConfig.FastCheckParams, out CheckTime, CheckNames);
ParseFastCheckEndDelayString(finishDetectConfig.CheckEndDelay, out DelayTime, DelayTimes);
BattleEndProgressBarColor = ParseStringToTuple(finishDetectConfig.BattleEndProgressBarColor, (95, 235, 255));
BattleEndProgressBarColorTolerance = ParseSingleOrCommaSeparated(finishDetectConfig.BattleEndProgressBarColorTolerance, (6, 6, 6));
}
public (int, int, int) BattleEndProgressBarColor{ get; }
public (int, int, int) BattleEndProgressBarColorTolerance{ get; }
public (int, int, int) BattleEndProgressBarColor { get; }
public (int, int, int) BattleEndProgressBarColorTolerance { get; }
public static void ParseCheckTimeString(
string input,
out double checkTime,
@@ -66,6 +72,7 @@ public class AutoFightTask : ISoloTask
{
return; // 直接返回
}
var uniqueNames = new HashSet<string>(); // 用于临时去重的集合
// 按分号分割字符串
@@ -88,6 +95,7 @@ public class AutoFightTask : ISoloTask
names.AddRange(uniqueNames); // 将集合转换为列表
}
public static void ParseFastCheckEndDelayString(
string input,
out int delayTime,
@@ -97,9 +105,9 @@ public class AutoFightTask : ISoloTask
if (string.IsNullOrEmpty(input))
{
return; // 直接返回
}
// 分割字符串,以分号为分隔符
var segments = input.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
@@ -128,7 +136,7 @@ public class AutoFightTask : ISoloTask
}
}
static bool IsSingleNumber(string input, out int result)
{
return int.TryParse(input, out result);
@@ -160,10 +168,10 @@ public class AutoFightTask : ISoloTask
// 如果解析失败,返回默认值
return defaultValue;
}
}
private TaskFightFinishDetectConfig _finishDetectConfig;
public AutoFightTask(AutoFightParam taskParam)
{
_taskParam = taskParam;
@@ -174,11 +182,11 @@ public class AutoFightTask : ISoloTask
_predictor = BgiYoloV8PredictorFactory.GetPredictor(@"Assets\Model\World\bgi_world.onnx");
}
_finishDetectConfig=new TaskFightFinishDetectConfig(_taskParam.FinishDetectConfig);
_finishDetectConfig = new TaskFightFinishDetectConfig(_taskParam.FinishDetectConfig);
}
// 方法1:判断是否是单个数字
/*public int delayTime=1500;
public Dictionary<string, int> delayTimes = new();
public double checkTime = 5;
@@ -203,17 +211,19 @@ public class AutoFightTask : ISoloTask
combatScenes.BeforeTask(cts2.Token);
TimeSpan fightTimeout = TimeSpan.FromSeconds(_taskParam.Timeout); // 战斗超时时间
Stopwatch timeoutStopwatch = Stopwatch.StartNew();
Stopwatch checkFightFinishStopwatch = Stopwatch.StartNew();
TimeSpan checkFightFinishTime = TimeSpan.FromSeconds(_finishDetectConfig.CheckTime); //检查战斗超时时间的超时时间
//战斗前检查,可做成配置
/* if (await CheckFightFinish()) {
return;
}*/
var fightEndFlag = false;
string lastFighttName = "";
//统计切换人打架次数
var countFight = 0;
// 战斗操作
var fightTask = Task.Run(async () =>
{
@@ -221,7 +231,6 @@ public class AutoFightTask : ISoloTask
{
while (!cts2.Token.IsCancellationRequested)
{
// 通用化战斗策略
for (var i = 0; i < combatCommands.Count; i++)
{
@@ -234,21 +243,23 @@ public class AutoFightTask : ISoloTask
}
command.Execute(combatScenes);
//统计战斗人次
if (i == combatCommands.Count - 1 || command.Name != combatCommands[i + 1].Name)
{
countFight++;
}
lastFighttName = command.Name;
if (!fightEndFlag && _taskParam is { FightFinishDetectEnabled: true } )
if (!fightEndFlag && _taskParam is { FightFinishDetectEnabled: true })
{
//处于最后一个位置,或者当前执行人和下一个人名字不一样的情况,满足一定条件(开启快速检查,并且检查时间大于0或人名存在配置)检查战斗
if (i==combatCommands.Count - 1
if (i == combatCommands.Count - 1
|| (
_finishDetectConfig.FastCheckEnabled && command.Name!=combatCommands[i+1].Name &&
((_finishDetectConfig.CheckTime>0 && checkFightFinishStopwatch.Elapsed>checkFightFinishTime)
|| _finishDetectConfig.CheckNames.Contains(command.Name))
))
_finishDetectConfig.FastCheckEnabled && command.Name != combatCommands[i + 1].Name &&
((_finishDetectConfig.CheckTime > 0 && checkFightFinishStopwatch.Elapsed > checkFightFinishTime)
|| _finishDetectConfig.CheckNames.Contains(command.Name))
))
{
checkFightFinishStopwatch.Restart();
var delayTime = _finishDetectConfig.DelayTime;
if (_finishDetectConfig.DelayTimes.TryGetValue(command.Name, out var time))
@@ -268,12 +279,11 @@ public class AutoFightTask : ISoloTask
fightEndFlag = await CheckFightFinish(delayTime);
}
}
if (fightEndFlag)
{
break;
}
}
@@ -329,33 +339,30 @@ public class AutoFightTask : ISoloTask
var kazuha = combatScenes.Avatars.FirstOrDefault(a => a.Name == "枫原万叶");
if (kazuha != null)
{
var time = DateTime.UtcNow - kazuha.LastSkillTime;
//当万叶最后一个出招,并且cd大于3时,此时不再触发万叶拾取
if (!(lastFighttName== "枫原万叶" && time.TotalSeconds>3))
var time = DateTime.UtcNow - kazuha.LastSkillTime;
//当万叶cd大于3时或战斗人次少于2时(通常无怪物情况下),此时不再触发万叶拾取,
if (!(countFight < 2 || lastFighttName == "枫原万叶" && time.TotalSeconds > 3))
{
Logger.LogInformation("使用枫原万叶长E拾取掉落物");
await Delay(300, ct);
if (kazuha.TrySwitch())
{
if (time.TotalMilliseconds > 0 && time.TotalSeconds <= kazuha.SkillHoldCd)
{
Logger.LogInformation("枫原万叶长E技能可能处于冷却中,等待 {Time} s",time.TotalSeconds);
await Delay((int)Math.Ceiling(time.TotalMilliseconds), ct);
}
kazuha.UseSkill(true);
await Task.Delay(100);
Simulation.SendInput.Mouse.LeftButtonClick();
await Delay(1500, ct);
if (time.TotalMilliseconds > 0 && time.TotalSeconds <= kazuha.SkillHoldCd)
{
Logger.LogInformation("枫原万叶长E技能可能处于冷却中,等待 {Time} s", time.TotalSeconds);
await Delay((int)Math.Ceiling(time.TotalMilliseconds), ct);
}
kazuha.UseSkill(true);
await Task.Delay(100);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1500, ct);
}
}
else
{
Logger.LogInformation("最后一次由万叶出招,不再重复拾取!");
Logger.LogInformation((countFight < 2 ? "首个人出招就结束战斗,应该无怪物" : "距最近一次万叶出招,时间过短") + ",跳过此次万叶拾取!");
}
}
}
@@ -368,11 +375,7 @@ public class AutoFightTask : ISoloTask
private void LogScreenResolution()
{
var gameScreenSize = SystemControl.GetGameScreenRect(TaskContext.Instance().GameHandle);
if (gameScreenSize.Width * 9 != gameScreenSize.Height * 16)
{
Logger.LogWarning("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏可能无法正常使用自动战斗功能 !", gameScreenSize.Width, gameScreenSize.Height);
}
AssertUtils.CheckGameResolution("自动战斗");
}
static bool AreDifferencesWithinBounds((int, int, int) a, (int, int, int) b, (int, int, int) c)
@@ -383,7 +386,7 @@ public class AutoFightTask : ISoloTask
Math.Abs(a.Item3 - b.Item3) < c.Item3;
}
private async Task<bool> CheckFightFinish(int delayTime=1500)
private async Task<bool> CheckFightFinish(int delayTime = 1500)
{
// YOLO 判断血条和怪物位置
// if (HasFightFlagByYolo(CaptureToRectArea()))
@@ -416,24 +419,32 @@ public class AutoFightTask : ISoloTask
}
}
**/
await Delay(delayTime, _ct);
Logger.LogInformation("按L检查战斗是否结束");
Logger.LogInformation("打开编队界面检查战斗是否结束");
// 最终方案确认战斗结束
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_L);
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
await Delay(450, _ct);
var ra = CaptureToRectArea();
var b3 = ra.SrcMat.At<Vec3b>(50, 790);
if (AreDifferencesWithinBounds(_finishDetectConfig.BattleEndProgressBarColor, (b3.Item0, b3.Item1, b3.Item2), _finishDetectConfig.BattleEndProgressBarColorTolerance))
var b3 = ra.SrcMat.At<Vec3b>(50, 790); //进度条颜色
var whiteTile = ra.SrcMat.At<Vec3b>(50, 772); //白块
if (IsWhite(whiteTile.Item2, whiteTile.Item1, whiteTile.Item0) && IsYellow(b3.Item2, b3.Item1, b3.Item0) /* AreDifferencesWithinBounds(_finishDetectConfig.BattleEndProgressBarColor, (b3.Item0, b3.Item1, b3.Item2), _finishDetectConfig.BattleEndProgressBarColorTolerance)*/)
{
Logger.LogInformation("识别到战斗结束");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
Simulation.SendInput.SimulateAction(GIActions.Drop);
return true;
}
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
Simulation.SendInput.SimulateAction(GIActions.Drop);
Logger.LogInformation($"未识别到战斗结束{b3.Item0},{b3.Item1},{b3.Item2}");
/**
if (!Bv.IsInMainUi(ra))
{
// 如果不在主界面,说明异常,直接结束战斗继续下一步(路径追踪下一步会进入异常处理)
Logger.LogInformation("当前不在主界面,直接结束战斗!");
return true;
}**/
_lastFightFlagTime = DateTime.Now;
return false;
@@ -442,6 +453,24 @@ public class AutoFightTask : ISoloTask
return false;
}
bool IsYellow(int r, int g, int b)
{
//Logger.LogInformation($"IsYellow({r},{g},{b})");
// 黄色范围:R高,G高,B低
return (r >= 200 && r <= 255) &&
(g >= 200 && g <= 255) &&
(b >= 0 && b <= 100);
}
bool IsWhite(int r, int g, int b)
{
//Logger.LogInformation($"IsWhite({r},{g},{b})");
// 白色范围:R高,G高,B低
return (r >= 240 && r <= 255) &&
(g >= 240 && g <= 255) &&
(b >= 240 && b <= 255);
}
private bool HasFightFlagByYolo(ImageRegion imageRegion)
{
// if (RuntimeHelper.IsDebug)
@@ -2,6 +2,7 @@
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoFight.Config;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
@@ -11,10 +12,12 @@ using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
@@ -88,6 +91,7 @@ public class Avatar
/// </summary>
public CombatScenes CombatScenes { get; set; }
public Avatar(CombatScenes combatScenes, string name, int index, Rect nameRect)
{
CombatScenes = combatScenes;
@@ -115,14 +119,14 @@ public class Avatar
{
Logger.LogWarning("检测到复苏界面,存在角色被击败,前往七天神像复活");
// 先打开地图
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE); // NOTE: 此处按下Esc是为了关闭复苏界面,无需改键
Sleep(600, Ct);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_M);
Simulation.SendInput.SimulateAction(GIActions.OpenMap);
// tp 到七天神像复活
var tpTask = new TpTask(Ct);
tpTask.Tp(TpTask.ReviveStatueOfTheSevenPointX, TpTask.ReviveStatueOfTheSevenPointY, true).Wait(Ct);
tpTask.TpToStatueOfTheSeven().Wait(Ct);
throw new Exception("检测到复苏界面,存在角色被击败,前往七天神像复活");
throw new RetryException("检测到复苏界面,存在角色被击败,前往七天神像复活");
}
}
@@ -148,7 +152,26 @@ public class Avatar
return;
}
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_1 + (byte)Index - 1);
switch (Index)
{
case 1:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember1);
break;
case 2:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember2);
break;
case 3:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember3);
break;
case 4:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember4);
break;
case 5:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember5);
break;
default:
break;
}
// Debug.WriteLine($"切换到{Index}号位");
// Cv2.ImWrite($"log/切换.png", region.SrcMat);
Sleep(250, Ct);
@@ -184,7 +207,26 @@ public class Avatar
return true;
}
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_1 + (byte)Index - 1);
switch (Index)
{
case 1:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember1);
break;
case 2:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember2);
break;
case 3:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember3);
break;
case 4:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember4);
break;
case 5:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember5);
break;
default:
break;
}
Sleep(250, Ct);
}
@@ -209,7 +251,26 @@ public class Avatar
return;
}
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_1 + (byte)Index - 1);
switch (Index)
{
case 1:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember1);
break;
case 2:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember2);
break;
case 3:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember3);
break;
case 4:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember4);
break;
case 5:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember5);
break;
default:
break;
}
Sleep(250);
}
}
@@ -304,7 +365,7 @@ public class Avatar
return;
}
AutoFightContext.Instance.Simulator.LeftButtonClick();
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack);
ms -= 200;
Sleep(200, Ct);
}
@@ -326,7 +387,7 @@ public class Avatar
{
if (Name == "纳西妲")
{
AutoFightContext.Instance.Simulator.KeyDown(User32.VK.VK_E);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
Sleep(300, Ct);
for (int j = 0; j < 10; j++)
{
@@ -335,22 +396,22 @@ public class Avatar
}
Sleep(300); // 持续操作不应该被cts取消
AutoFightContext.Instance.Simulator.KeyUp(User32.VK.VK_E);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
}
else if (Name == "坎蒂丝")
{
AutoFightContext.Instance.Simulator.KeyDown(User32.VK.VK_E);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
Thread.Sleep(3000);
AutoFightContext.Instance.Simulator.KeyUp(User32.VK.VK_E);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
}
else
{
AutoFightContext.Instance.Simulator.LongKeyPress(User32.VK.VK_E);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.Hold);
}
}
else
{
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_E);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyPress);
}
Sleep(200, Ct);
@@ -394,7 +455,7 @@ public class Avatar
return;
}
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_Q);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalBurst);
Sleep(200, Ct);
var region = CaptureToRectArea();
@@ -449,9 +510,9 @@ public class Avatar
ms = 200;
}
AutoFightContext.Instance.Simulator.RightButtonDown();
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SprintMouse, KeyType.KeyDown);
Sleep(ms); // 冲刺不能被cts取消
AutoFightContext.Instance.Simulator.RightButtonUp();
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SprintMouse, KeyType.KeyUp);
}
public void Walk(string key, int ms)
@@ -464,19 +525,19 @@ public class Avatar
User32.VK vk = User32.VK.VK_NONAME;
if (key == "w")
{
vk = User32.VK.VK_W;
vk = GIActions.MoveForward.ToActionKey().ToVK();
}
else if (key == "s")
{
vk = User32.VK.VK_S;
vk = GIActions.MoveBackward.ToActionKey().ToVK();
}
else if (key == "a")
{
vk = User32.VK.VK_A;
vk = GIActions.MoveLeft.ToActionKey().ToVK();
}
else if (key == "d")
{
vk = User32.VK.VK_D;
vk = GIActions.MoveRight.ToActionKey().ToVK();
}
if (vk == User32.VK.VK_NONAME)
@@ -513,7 +574,7 @@ public class Avatar
/// </summary>
public void Jump()
{
AutoFightContext.Instance.Simulator.KeyPress(User32.VK.VK_SPACE);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.Jump);
}
/// <summary>
@@ -529,7 +590,7 @@ public class Avatar
if (Name == "那维莱特")
{
var dpi = TaskContext.Instance().DpiScale;
AutoFightContext.Instance.Simulator.LeftButtonDown();
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyDown);
while (ms >= 0)
{
if (Ct is { IsCancellationRequested: true })
@@ -542,13 +603,13 @@ public class Avatar
Sleep(50); // 持续操作不应该被cts取消
}
AutoFightContext.Instance.Simulator.LeftButtonUp();
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyUp);
}
else
{
AutoFightContext.Instance.Simulator.LeftButtonDown();
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyDown);
Sleep(ms); // 持续操作不应该被cts取消
AutoFightContext.Instance.Simulator.LeftButtonUp();
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyUp);
}
}
@@ -51,6 +51,7 @@ public class CombatScenes : IDisposable
/// <param name="imageRegion">完整游戏画面的捕获截图</param>
public CombatScenes InitializeTeam(ImageRegion imageRegion)
{
AssertUtils.CheckGameResolution();
// 优先取配置
if (!string.IsNullOrEmpty(TaskContext.Instance().Config.AutoFightConfig.TeamNames))
{
@@ -166,15 +167,15 @@ public class CombatScenes : IDisposable
if (result.TopClass.Confidence < 0.51)
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence},结果:{result.TopClass.Name.Name}");
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读了文档中的《快速上手》!");
}
}
else
{
if (result.TopClass.Confidence < 0.8)
if (result.TopClass.Confidence < 0.7)
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence},结果:{result.TopClass.Name.Name}");
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读了文档中的《快速上手》!");
}
}
@@ -27,38 +27,41 @@ public class CombatCommand
Method = Method.GetEnumByCode(method);
var parameters = command.Substring(startIndex + 1, endIndex - startIndex - 1);
Args = new List<string>(parameters.Split(',', StringSplitOptions.TrimEntries));
// 校验参数
if (Method == Method.Walk)
{
AssertUtils.IsTrue(Args.Count == 2, "walk方法必须有两个入参,第一个参数是方向,第二个参数是行走时间。例:walk(s, 0.2)");
var s = double.Parse(Args[1]);
AssertUtils.IsTrue(s > 0, "行走时间必须大于0");
}
else if (Method == Method.W || Method == Method.A || Method == Method.S || Method == Method.D)
{
AssertUtils.IsTrue(Args.Count == 1, "w/a/s/d方法必须有一个入参,代表行走时间。例:d(0.5)");
}
else if (Method == Method.MoveBy)
{
AssertUtils.IsTrue(Args.Count == 2, "moveby方法必须有两个入参,分别是x和y。例:moveby(100, 100))");
}
else if (Method == Method.KeyDown || Method == Method.KeyUp || Method == Method.KeyPress)
{
AssertUtils.IsTrue(Args.Count == 1, $"{Method.Alias[0]}方法必须有一个入参,代表按键");
try
{
User32Helper.ToVk(Args[0]);
}
catch
{
throw new ArgumentException($"{Method.Alias[0]}方法的入参必须是VirtualKeyCodes枚举中的值,当前入参 {Args[0]} 不合法");
}
}
Args = [..parameters.Split(',', StringSplitOptions.TrimEntries)];
}
else
{
Method = Method.GetEnumByCode(command);
Args = [];
}
// 校验参数
if (Method == Method.Walk)
{
AssertUtils.IsTrue(Args.Count == 2, "walk方法必须有两个入参,第一个参数是方向,第二个参数是行走时间。例:walk(s, 0.2)");
var s = double.Parse(Args[1]);
AssertUtils.IsTrue(s > 0, "行走时间必须大于0");
}
else if (Method == Method.W || Method == Method.A || Method == Method.S || Method == Method.D)
{
AssertUtils.IsTrue(Args.Count == 1, "w/a/s/d方法必须有一个入参,代表行走时间。例:d(0.5)");
}
else if (Method == Method.MoveBy)
{
AssertUtils.IsTrue(Args.Count == 2, "moveby方法必须有两个入参,分别是x和y。例:moveby(100, 100))");
}
else if (Method == Method.KeyDown || Method == Method.KeyUp || Method == Method.KeyPress)
{
AssertUtils.IsTrue(Args.Count == 1, $"{Method.Alias[0]}方法必须有一个入参,代表按键");
try
{
User32Helper.ToVk(Args[0]);
}
catch
{
throw new ArgumentException($"{Method.Alias[0]}方法的入参必须是VirtualKeyCodes枚举中的值,当前入参 {Args[0]} 不合法");
}
}
}
@@ -57,11 +57,11 @@ public class Duel
public void Run(CancellationToken ct)
{
LogScreenResolution();
try
{
AutoGeniusInvokationAssets.DestroyInstance();
LogScreenResolution();
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Started().Build()); // TODO 需要移动
GeniusInvokationControl.GetInstance().Init(ct);
@@ -437,6 +437,7 @@ public class Duel
if (gameScreenSize.Width != 1920 || gameScreenSize.Height != 1080)
{
_logger.LogWarning("游戏窗口分辨率不是 1920x1080 !当前分辨率为 {Width}x{Height} , 非 1920x1080 分辨率的游戏可能无法正常使用自动七圣召唤 !", gameScreenSize.Width, gameScreenSize.Height);
throw new System.Exception("游戏窗口分辨率不是 1920x1080");
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -11,6 +11,10 @@ public class AutoMusicAssets : BaseAssets<AutoMusicAssets>
public RecognitionObject BtnPause;
public RecognitionObject AlbumMusicComplate;
public RecognitionObject BtnList;
public RecognitionObject MusicCanorusLevel1;
public RecognitionObject MusicCanorusLevel2;
public RecognitionObject MusicCanorusLevel3;
public RecognitionObject MusicCanorusLevel4;
private AutoMusicAssets()
{
@@ -42,5 +46,39 @@ public class AutoMusicAssets : BaseAssets<AutoMusicAssets>
TemplateImageMat = GameTaskManager.LoadAssetImage(@"AutoMusicGame", "btn_list.png"),
RegionOfInterest = CaptureRect.CutRightBottom(0.4, 0.2),
}.InitTemplate();
var musicCanorusTemplateImageMat = GameTaskManager.LoadAssetImage(@"AutoMusicGame", "music_canorus.png");
MusicCanorusLevel1 = new RecognitionObject
{
Name = "MusicCanorusLevel1",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = musicCanorusTemplateImageMat,
RegionOfInterest = new Rect((int)(450 * AssetScale), (int)(430 * AssetScale), (int)(200 * AssetScale),
(int)(60 * AssetScale)),
}.InitTemplate();
MusicCanorusLevel2 = new RecognitionObject
{
Name = "MusicCanorusLevel2",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = musicCanorusTemplateImageMat,
RegionOfInterest = new Rect((int)(450 * AssetScale), (int)(520 * AssetScale), (int)(200 * AssetScale),
(int)(60 * AssetScale)),
}.InitTemplate();
MusicCanorusLevel3 = new RecognitionObject
{
Name = "MusicCanorusLevel3",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = musicCanorusTemplateImageMat,
RegionOfInterest = new Rect((int)(450 * AssetScale), (int)(610 * AssetScale), (int)(200 * AssetScale),
(int)(60 * AssetScale)),
}.InitTemplate();
MusicCanorusLevel4 = new RecognitionObject
{
Name = "MusicCanorusLevel4",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = musicCanorusTemplateImageMat,
RegionOfInterest = new Rect((int)(450 * AssetScale), (int)(690 * AssetScale), (int)(200 * AssetScale),
(int)(60 * AssetScale)),
}.InitTemplate();
}
}
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoMusicGame.Assets;
@@ -39,62 +40,95 @@ public class AutoAlbumTask(AutoMusicGameParam taskParam) : ISoloTask
{
throw new Exception("当前未处于专辑界面,请在专辑界面运行本任务");
}
// 12个音乐
for (int i = 0; i < 13; i++)
var musicLevel = TaskContext.Instance().Config.AutoMusicGameConfig.MusicLevel;
if (string.IsNullOrEmpty(musicLevel))
{
musicLevel = "传说";
}
Logger.LogInformation("自动音游乐曲难度等级:{Text}", musicLevel);
// 遍历4个难度等级
var defaultDifficultyLevels = new[]
{
("普通", 480, 600, AutoMusicAssets.Instance.MusicCanorusLevel1),
("困难", 800, 600, AutoMusicAssets.Instance.MusicCanorusLevel2),
("大师", 1150, 600, AutoMusicAssets.Instance.MusicCanorusLevel3),
("传说", 1400, 600, AutoMusicAssets.Instance.MusicCanorusLevel4)
};
var difficultyLevels = defaultDifficultyLevels;
if (musicLevel != "所有")
{
difficultyLevels = [Array.Find(defaultDifficultyLevels, level => level.Item1 == musicLevel)];
}
using var doneRa = CaptureToRectArea().Find(AutoMusicAssets.Instance.AlbumMusicComplate);
if (doneRa.IsExist())
foreach (var (difficultyName, xPos, yPos, canorusAsset) in difficultyLevels)
{
Logger.LogInformation("开始演奏{Difficulty}难度的乐曲", difficultyName);
// 每个难度12首曲子
for (int i = 0; i < 13; i++)
{
Logger.LogInformation("当前乐曲{Num}所有奖励已领取,切换下一首", i + 1);
using var canoraRa = CaptureToRectArea().Find(canorusAsset);
if (canoraRa.IsExist())
{
Logger.LogInformation("乐曲{Num} - {Difficulty}级别:已完成【大音天籁】,切换下一首", i + 1, difficultyName);
GameCaptureRegion.GameRegion1080PPosClick(310, 220);
await Delay(800, ct);
continue;
}
Logger.LogInformation("第{Num}首{Difficulty}难度的乐曲:{Message}", i + 1, difficultyName, "没有完成【大音天籁】");
// 点击确认按钮
Bv.ClickWhiteConfirmButton(CaptureToRectArea());
await Delay(800, ct);
// 选择难度
GameCaptureRegion.GameRegion1080PPosClick(xPos, yPos);
await Delay(200, ct);
// 开始演奏
Bv.ClickWhiteConfirmButton(CaptureToRectArea());
await Delay(500, ct);
using var cts = new CancellationTokenSource();
ct.Register(cts.Cancel);
// 演奏结束检查任务
var checkTask = Task.Run(async () =>
{
while (!cts.Token.IsCancellationRequested)
{
await Delay(5000, ct); // 每5秒检查一次
using var listRa = CaptureToRectArea().Find(AutoMusicAssets.Instance.BtnList);
if (listRa.IsExist())
{
Logger.LogDebug("检测到返回列表按钮,演奏结束");
listRa.Click();
return;
}
}
}, cts.Token);
// 演奏任务
var musicTask = _autoMusicGameTask.StartWithOutInit(cts.Token);
// 等待任意一个任务完成
await Task.WhenAny(checkTask, musicTask);
await cts.CancelAsync();
Logger.LogInformation("第{Num}首{Difficulty}难度乐曲演奏完成", i + 1, difficultyName);
await Delay(2000, ct);
await Bv.WaitUntilFound(AutoMusicAssets.Instance.UiLeftTopAlbumIcon, ct);
Logger.LogDebug("切换到下一首乐曲");
GameCaptureRegion.GameRegion1080PPosClick(310, 220);
await Delay(800, ct);
continue;
}
Logger.LogInformation("当前乐曲{Num}存在未领取奖励,前往演奏", i + 1);
Bv.ClickWhiteConfirmButton(CaptureToRectArea());
await Delay(800, ct);
// 点击传说
GameCaptureRegion.GameRegion1080PPosClick(1400, 600);
await Delay(200, ct);
// 演奏
Bv.ClickWhiteConfirmButton(CaptureToRectArea());
await Delay(500, ct);
CancellationTokenSource cts = new();
ct.Register(cts.Cancel);
// 演奏结束检查任务
var checkTask = Task.Run(async () =>
{
while (!cts.Token.IsCancellationRequested)
{
await Delay(5000, ct); // n秒检查一次
using var listRa = CaptureToRectArea().Find(AutoMusicAssets.Instance.BtnList);
if (listRa.IsExist())
{
listRa.Click();
return;
}
}
}, cts.Token);
// 演奏任务
var musicTask = _autoMusicGameTask.StartWithOutInit(cts.Token);
// 等待任意一个任务完成
await Task.WhenAny(checkTask, musicTask);
await cts.CancelAsync();
Logger.LogInformation("当前乐曲{Num}演奏结束", i + 1);
await Delay(2000, ct);
await Bv.WaitUntilFound(AutoMusicAssets.Instance.UiLeftTopAlbumIcon, ct);
Logger.LogInformation("切换下一首");
GameCaptureRegion.GameRegion1080PPosClick(310, 220);
await Delay(800, ct);
Logger.LogInformation("完成{Difficulty}难度所有乐曲的演奏", difficultyName);
}
Logger.LogInformation("当前专辑所有乐曲演奏结束");
@@ -0,0 +1,17 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.GameTask.AutoMusicGame;
/// <summary>
/// 千音雅集配置
/// </summary>
[Serializable]
public partial class AutoMusicGameConfig : ObservableObject
{
// 乐曲级别
[ObservableProperty]
private string _musicLevel = "";
}
@@ -6,6 +6,7 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Helpers;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -243,12 +244,7 @@ public class AutoMusicGameTask(AutoMusicGameParam taskParam) : ISoloTask
public static void LogScreenResolution()
{
var gameScreenSize = SystemControl.GetGameScreenRect(TaskContext.Instance().GameHandle);
if (gameScreenSize.Width * 9 != gameScreenSize.Height * 16)
{
Logger.LogError("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏无法正常使用自动活动音游功能 !", gameScreenSize.Width, gameScreenSize.Height);
throw new Exception("游戏窗口分辨率不是 16:9");
}
AssertUtils.CheckGameResolution("自动音游");
Logger.LogInformation("{Name}:回到游戏主界面时记得关闭自动音游任务!", "千音雅集");
Logger.LogWarning("{Name}:默认的样式“轻漾涟漪”是{No}的!需要手动完成几首曲目获得{Money}千音币后兑换并使用胡桃样式“{Hutao}”!", "千音雅集", "不可用", 600, "疏影引蝶映梅红");
@@ -12,6 +12,15 @@ namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
internal class AutoFightHandler : IActionHandler
{
public async Task RunAsyncByScript(CancellationToken ct, WaypointForTrack? waypointForTrack = null, object? config = null)
{
if (!(config != null && config is PathingPartyConfig patyConfig && patyConfig is {AutoFightEnabled:true,JsScriptUseEnabled:true,SoloTaskUseFightEnabled:true} ))
{
config = null;
}
await StartFight(ct, config);
}
public async Task RunAsync(CancellationToken ct, WaypointForTrack? waypointForTrack = null, object? config = null)
{
await StartFight(ct, config);
@@ -22,7 +31,7 @@ internal class AutoFightHandler : IActionHandler
TaskControl.Logger.LogInformation("执行 {Text}", "自动战斗");
// 爷们要战斗
AutoFightParam taskParams = null;
if (config != null && config is PathingPartyConfig patyConfig && patyConfig.AutoFightEabled)
if (config != null && config is PathingPartyConfig patyConfig && patyConfig.AutoFightEnabled)
{
//替换配置为路径追踪
@@ -15,7 +15,7 @@ public class CombatScriptHandler : IActionHandler
{
if (waypointForTrack is { CombatScript: not null })
{
Logger.LogInformation("执行 {Text}", "战斗策略脚本");
Logger.LogInformation("执行 {Text}", "简易策略脚本");
var combatScript = waypointForTrack.CombatScript;
var combatScenes = await RunnerContext.Instance.GetCombatScenes(ct);
if (combatScenes == null)
@@ -41,7 +41,7 @@ public class CombatScriptHandler : IActionHandler
}
else
{
Logger.LogError("战斗脚本action_params内容为空");
Logger.LogError("策略脚本action_params内容为空");
}
}
@@ -63,7 +63,7 @@ public class ElementalCollectHandler(ElementalType elementalType) : IActionHandl
}
else
{
Logger.LogError("切人失败,无法进行{Element}元素采集", elementalType.ToString());
Logger.LogError("切人失败,无法进行{Element}元素采集", elementalType.ToChinese());
}
break;
@@ -117,6 +117,7 @@ public class ElementalCollectAvatarConfigs
new ElementalCollectAvatar("琳妮特", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("温迪", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("琴", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("早柚", ElementalType.Anemo, false, true),
];
public static ElementalCollectAvatar? Get(string name, ElementalType type) => Lists.FirstOrDefault(x => x.Name == name && x.ElementalType == type);
@@ -7,6 +7,7 @@ using BetterGenshinImpact.GameTask.AutoPathing.Model;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Simulator.Extensions;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
@@ -19,7 +20,7 @@ public class ElementalSkillHandler : IActionHandler
public async Task RunAsync(CancellationToken ct, WaypointForTrack? waypointForTrack = null, object? config = null)
{
Logger.LogInformation("执行 {Text}", "释放元素战技");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
await Delay(1000, ct);
}
}
@@ -3,6 +3,7 @@ using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
@@ -55,7 +56,7 @@ public class NahidaCollectHandler : IActionHandler
await Delay(200, ct);
// 按住E技能 无死角扫码
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
await Delay(200, ct);
// 先地面来一圈
@@ -77,7 +78,7 @@ public class NahidaCollectHandler : IActionHandler
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
await Delay(30, ct);
}
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
lastETime = DateTime.Now;
@@ -1,5 +1,6 @@
using System;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
@@ -18,7 +19,7 @@ public class NormalAttackHandler : IActionHandler
public async Task RunAsync(CancellationToken ct, WaypointForTrack? waypointForTrack = null, object? config = null)
{
Logger.LogInformation("执行 {Text}", "普通攻击");
Simulation.SendInput.Mouse.LeftButtonClick();
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1000, ct);
}
}
@@ -9,6 +9,7 @@ using BetterGenshinImpact.Helpers;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Simulator.Extensions;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
@@ -47,7 +48,7 @@ public class PickAroundHandler() : IActionHandler
public async Task MoveCircle(double edgeT, int n)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_A);
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyDown);
await Delay(30, _ct);
while (n-- > 0)
{
@@ -55,7 +56,7 @@ public class PickAroundHandler() : IActionHandler
await Delay((int)Math.Round(edgeT), _ct);
}
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_A);
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
await Delay(200, _ct);
}
@@ -67,9 +68,9 @@ public class PickAroundHandler() : IActionHandler
await Delay(500, _ct);
if (ms > 0)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
await Delay(ms, _ct);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
await Delay(200, _ct);
}
}
@@ -80,8 +81,8 @@ public class PickAroundHandler() : IActionHandler
double y = oldRadius * Math.Sin(angle);
Simulation.SendInput.Mouse.MiddleButtonClick();
await Delay(500, _ct);
await MoveAfterTurn(User32.VK.VK_S, (int)Math.Round(y) + 200);
await MoveAfterTurn(User32.VK.VK_A, (int)Math.Round(x));
await MoveAfterTurn(GIActions.MoveBackward.ToActionKey().ToVK(), (int)Math.Round(y) + 200);
await MoveAfterTurn(GIActions.MoveLeft.ToActionKey().ToVK(), (int)Math.Round(x));
}
}
@@ -3,6 +3,7 @@ using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
@@ -25,7 +26,7 @@ public class UpDownGrabLeaf : IActionHandler
// kbPress('w'); // 飞行
while (i > 0 && !ct.IsCancellationRequested)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_T);
Simulation.SendInput.SimulateAction(GIActions.InteractionInSomeMode, KeyType.KeyDown);
if (i % 10 == 0)
{
y = -y;
@@ -18,6 +18,7 @@ public class ActionEnum(string code, string msg)
public static readonly ActionEnum CombatScript = new("combat_script", "战斗策略脚本"); // 这个必须要 action_params 里面有脚本
public static readonly ActionEnum Mining = new("mining", "挖矿");
public static readonly ActionEnum LogOutput = new("log_output", "输出日志");
// 还有要加入的其他动作
// 滚轮F
@@ -2,6 +2,7 @@
using System;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using System.Diagnostics.Eventing.Reader;
namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
@@ -22,6 +23,7 @@ public class WaypointForTrack : Waypoint
/// 存在 combat_script 的 action 的话,这个值会存在
/// </summary>
public CombatScript? CombatScript { get; set; }
public string? LogInfo { get; set; }
public WaypointForTrack(Waypoint waypoint)
{
@@ -40,5 +42,9 @@ public class WaypointForTrack : Waypoint
{
CombatScript = CombatScriptParser.ParseContext(str, false);
}
if (waypoint.Action == ActionEnum.LogOutput.Code && waypoint.ActionParams is not null)
{
LogInfo = waypoint.ActionParams;
}
}
}
@@ -30,6 +30,7 @@ using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static BetterGenshinImpact.GameTask.SystemControl;
using ActionEnum = BetterGenshinImpact.GameTask.AutoPathing.Model.Enum.ActionEnum;
using BetterGenshinImpact.Core.Simulator.Extensions;
namespace BetterGenshinImpact.GameTask.AutoPathing;
@@ -142,30 +143,33 @@ public class PathExecutor
{
return;
}
InitializePathing(task);
// 转换、按传送点分割路径
var waypointsList = ConvertWaypointsForTrack(task.Positions);
await Delay(100, ct);
Navigation.WarmUp(); // 提前加载地图特征点
foreach (var waypoints in waypointsList)
foreach (var waypoints in waypointsList) // 按传送点分割的路径
{
CurWaypoints = (waypointsList.FindIndex(wps => wps == waypoints), waypoints);
for (var i = 0; i < RetryTimes; i++)
{
try
{
await ResolveAnomalies(); // 异常场景处理
foreach (var waypoint in waypoints)
foreach (var waypoint in waypoints) // 一条路径
{
CurWaypoint = (waypoints.FindIndex(wps => wps == waypoint), waypoint);
TryCloseSkipOtherOperations();
await RecoverWhenLowHp(waypoint); // 低血量恢复
if (waypoint.Action == ActionEnum.LogOutput.Code)
{
Logger.LogInformation(waypoint.LogInfo);
}
if (waypoint.Type == WaypointType.Teleport.Code)
{
await HandleTeleportWaypoint(waypoint);
@@ -178,18 +182,21 @@ public class PathExecutor
await MoveTo(waypoint);
if (waypoint.Type == WaypointType.Target.Code
// 除了 fight mining 之外的 action 都需要接近
// 除了 fight mining stop_flying 之外的 action 都需要接近
|| (!string.IsNullOrEmpty(waypoint.Action)
&& waypoint.Action != ActionEnum.NahidaCollect.Code
&& waypoint.Action != ActionEnum.Fight.Code
&& waypoint.Action != ActionEnum.CombatScript.Code
&& waypoint.Action != ActionEnum.Mining.Code))
{
await MoveCloseTo(waypoint);
if (waypoint.Action != ActionEnum.Fight.Code) // 战斗action强制不接近
{
await MoveCloseTo(waypoint);
}
}
//skipOtherOperations如果重试,则跳过相关操作
if (!string.IsNullOrEmpty(waypoint.Action) && !_skipOtherOperations)
//skipOtherOperations如果重试,则跳过相关操作,
if ((!string.IsNullOrEmpty(waypoint.Action) && !_skipOtherOperations) || waypoint.Action == ActionEnum.CombatScript.Code)
{
// 执行 action
await AfterMoveToTarget(waypoint);
@@ -328,7 +335,7 @@ public class PathExecutor
if (!string.IsNullOrEmpty(RunnerContext.Instance.PartyName))
{
// 非空的情况下,先tp到安全位置(回血的七天神像)
await new TpTask(ct).Tp(TpTask.ReviveStatueOfTheSevenPointX, TpTask.ReviveStatueOfTheSevenPointY, true);
await new TpTask(ct).TpToStatueOfTheSeven();
}
var success = await new SwitchPartyTask().Start(partyName, ct);
@@ -471,9 +478,9 @@ public class PathExecutor
if (avatar.TrySwitch())
{
//1命白术能两次
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
await Delay(800, ct);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
await Delay(800, ct);
await SwitchAvatar(PartyConfig.MainAvatarIndex);
await Delay(4000, ct);
@@ -486,7 +493,7 @@ public class PathExecutor
{
if (avatar.TrySwitch())
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
await Delay(11000, ct);
await SwitchAvatar(PartyConfig.MainAvatarIndex);
return true;
@@ -498,10 +505,10 @@ public class PathExecutor
{
if (avatar.TrySwitch())
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
await Delay(500, ct);
//尝试Q全队回血
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_Q);
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);
//单人血只给行走位加血
await SwitchAvatar(PartyConfig.MainAvatarIndex);
await Delay(5000, ct);
@@ -543,7 +550,7 @@ public class PathExecutor
{
// tp 到七天神像回血
var tpTask = new TpTask(ct);
await tpTask.Tp(TpTask.ReviveStatueOfTheSevenPointX, TpTask.ReviveStatueOfTheSevenPointY, true);
await tpTask.TpToStatueOfTheSeven();
await Delay(3000, ct);
Logger.LogInformation("HP恢复完成");
}
@@ -575,15 +582,14 @@ public class PathExecutor
var num = 0;
// 按下w,一直走
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
while (!ct.IsCancellationRequested)
{
num++;
var now = DateTime.UtcNow;
if ((now - startTime).TotalSeconds > 240)
if ((DateTime.UtcNow - startTime).TotalSeconds > 240)
{
Logger.LogWarning("执行超时,跳过路径点");
break;
Logger.LogWarning("执行超时,放弃此次追踪");
throw new RetryException("路径点执行超时,放弃整条路径");
}
screen = CaptureToRectArea();
@@ -617,9 +623,9 @@ public class PathExecutor
// 非攀爬状态下,检测是否卡死(脱困触发器)
if (waypoint.MoveMode != MoveModeEnum.Climb.Code)
{
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
if ((DateTime.UtcNow - lastPositionRecord).TotalMilliseconds > 1000)
{
lastPositionRecord = now;
lastPositionRecord = DateTime.UtcNow;
prevPositions.Add(position);
if (prevPositions.Count > 8)
{
@@ -637,7 +643,7 @@ public class PathExecutor
//调用脱困代码,由TrapEscaper接管移动
await _trapEscaper.RotateAndMove();
await _trapEscaper.MoveTo(waypoint);
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Logger.LogInformation("卡死脱离结束");
continue;
}
@@ -657,7 +663,7 @@ public class PathExecutor
if (!isFlying)
{
Debug.WriteLine("未进入飞行状态,按下空格");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
Simulation.SendInput.SimulateAction(GIActions.Jump);
await Delay(200, ct);
}
@@ -666,7 +672,7 @@ public class PathExecutor
if (waypoint.MoveMode == MoveModeEnum.Jump.Code)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
Simulation.SendInput.SimulateAction(GIActions.Jump);
await Delay(200, ct);
continue;
}
@@ -674,18 +680,13 @@ public class PathExecutor
// 只有设置为run才会一直疾跑
if (waypoint.MoveMode == MoveModeEnum.Run.Code)
{
if (distance > 20 != fastMode) // 距离大于30时可以使用疾跑/自由泳
if (distance > 25) // 距离大于25时可以使用疾跑
{
if (fastMode)
if (Math.Abs((fastModeColdTime - DateTime.UtcNow).TotalMilliseconds) > 1000) //冷却一会
{
Simulation.SendInput.Mouse.RightButtonUp();
fastModeColdTime = DateTime.UtcNow;
Simulation.SendInput.SimulateAction(GIActions.SprintMouse);
}
else
{
Simulation.SendInput.Mouse.RightButtonDown();
}
fastMode = !fastMode;
}
}
else if (waypoint.MoveMode != MoveModeEnum.Climb.Code) //否则自动短疾跑
@@ -700,7 +701,6 @@ public class PathExecutor
}
var ms = s * 1000;
Debug.WriteLine($"元素战技释放间隔:{(now - _elementalSkillLastUseTime).TotalMilliseconds}ms");
if ((DateTime.UtcNow - _elementalSkillLastUseTime).TotalMilliseconds > ms)
{
// 可能刚切过人在冷却时间内
@@ -715,12 +715,12 @@ public class PathExecutor
}
// 自动疾跑
if (distance > 20)
if (distance > 20 && PartyConfig.AutoRunEnabled)
{
if (Math.Abs((fastModeColdTime - now).TotalMilliseconds) > 2500) //冷却时间2.5s,回复体力用
if (Math.Abs((fastModeColdTime - DateTime.UtcNow).TotalMilliseconds) > 2500) //冷却时间2.5s,回复体力用
{
fastModeColdTime = now;
Simulation.SendInput.Mouse.RightButtonClick();
fastModeColdTime = DateTime.UtcNow;
Simulation.SendInput.SimulateAction(GIActions.SprintMouse);
}
}
}
@@ -730,7 +730,7 @@ public class PathExecutor
{
if ((DateTime.UtcNow - _useGadgetLastUseTime).TotalMilliseconds > PartyConfig.UseGadgetIntervalMs)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_Z);
Simulation.SendInput.SimulateAction(GIActions.QuickUseGadget);
_useGadgetLastUseTime = DateTime.UtcNow;
}
}
@@ -739,7 +739,7 @@ public class PathExecutor
}
// 抬起w键
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
}
private async Task UseElementalSkill()
@@ -762,29 +762,29 @@ public class PathExecutor
// 钟离往身后放柱子
if (avatar.Name == "钟离")
{
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
await Delay(50, ct);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_S);
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
await Delay(200, ct);
}
if (PartyConfig.GuardianElementalSkillLongPress)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
await Task.Delay(800); // 不能取消
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
await Delay(700, ct);
}
else
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_E);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
await Delay(300, ct);
}
// 钟离往身后放柱子 后继续走路
if (avatar.Name == "钟离")
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
}
}
@@ -798,8 +798,9 @@ public class PathExecutor
{
//下落攻击接近目的地
Logger.LogInformation("动作:下落攻击");
Simulation.SendInput.Mouse.LeftButtonClick();
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1000, ct);
return;
}
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
@@ -827,11 +828,14 @@ public class PathExecutor
targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
// 小碎步接近
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W).Sleep(60).KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Thread.Sleep(60);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
// Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W).Sleep(60).KeyUp(User32.VK.VK_W);
await Delay(20, ct);
}
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
// 到达目的地后停顿一秒
await Delay(1000, ct);
@@ -895,9 +899,10 @@ public class PathExecutor
if (position == new Point2f())
{
if (!Bv.IsInBigMapUi(imageRegion))
if (!Bv.IsInMainUi(imageRegion))
{
await ResolveAnomalies();
Logger.LogDebug("小地图位置定位失败,且当前不是主界面,进入异常处理");
await ResolveAnomalies(imageRegion);
}
}
@@ -908,8 +913,23 @@ public class PathExecutor
* 处理各种异常场景
* 需要保证耗时不能太高
*/
private async Task ResolveAnomalies()
private async Task ResolveAnomalies(ImageRegion? imageRegion = null)
{
if (imageRegion == null)
{
imageRegion = CaptureToRectArea();
}
// 一些异常界面处理
var cookRa = imageRegion.Find(AutoSkipAssets.Instance.CookRo);
var closeRa = imageRegion.Find(AutoSkipAssets.Instance.PageCloseMainRo);
if (cookRa.IsExist() || closeRa.IsExist())
{
Logger.LogInformation("检测到其他界面,使用ESC关闭界面");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
}
// 处理月卡
await _blessingOfTheWelkinMoonTask.Start(ct);
@@ -8,6 +8,7 @@ using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Simulator.Extensions;
namespace BetterGenshinImpact.GameTask.AutoPathing;
@@ -40,7 +41,7 @@ public class TrapEscaper(CancellationToken ct)
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 5);
// 按下w,一直走
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
while (!ct.IsCancellationRequested)
{
var now = DateTime.UtcNow;
@@ -70,7 +71,7 @@ public class TrapEscaper(CancellationToken ct)
//执行旋转
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 5);
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
//
//这里是随机角度的归零逻辑,在脱困执行一秒后将randomAngle设为0以将实际角度重置为正面向点位的角度
//其实就是在一段时间内进行角度的修改以实现自动避障
@@ -91,12 +92,12 @@ public class TrapEscaper(CancellationToken ct)
waypoint.MoveMode != MoveModeEnum.Fly.Code)
if (Bv.GetMotionStatus(screen) == MotionStatus.Climb)
{
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.Drop);
Sleep(75);
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_S);
Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyDown);
Sleep(700);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_S);
Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyUp);
LastActionTime = DateTime.UtcNow;
@@ -117,17 +118,17 @@ public class TrapEscaper(CancellationToken ct)
}
// 抬起w键
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
}
public async Task RotateAndMove()
{
IncreaseRandomAngle();
// 脱离攀爬状态
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.Drop);
await Delay(75, ct);
Simulation.SendInput.Mouse.LeftButtonClick();
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(500, ct);
TimeSpan timeSinceLastAction = DateTime.UtcNow - LastActionTime;
@@ -166,30 +167,30 @@ public class TrapEscaper(CancellationToken ct)
private void MoveBackward(int delay)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_S);
Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyDown);
Sleep(500);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
Simulation.SendInput.SimulateAction(GIActions.Jump);
Sleep(delay);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_S);
Simulation.SendInput.SimulateAction(GIActions.MoveBackward, KeyType.KeyUp);
}
private void MoveLeft(int delay)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_A);
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyDown);
Sleep(300);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
Simulation.SendInput.SimulateAction(GIActions.Jump);
Sleep(delay);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_A);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.Drop);
}
private void MoveRight(int delay)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_D);
Simulation.SendInput.SimulateAction(GIActions.MoveRight, KeyType.KeyDown);
Sleep(300);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
Simulation.SendInput.SimulateAction(GIActions.Jump);
Sleep(delay);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_D);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
Simulation.SendInput.SimulateAction(GIActions.MoveRight, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.Drop);
}
}
@@ -112,7 +112,7 @@ public partial class AutoPickTrigger : ITaskTrigger
if (_externalConfig is { ForceInteraction: true })
{
LogPick(content, "直接拾取");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_F);
Simulation.SendInput.Keyboard.KeyPress(AutoPickAssets.Instance.PickVk);
return;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

@@ -20,7 +20,8 @@ public class AutoSkipAssets : BaseAssets<AutoSkipAssets>
public RecognitionObject ExclamationIconRo;
public RecognitionObject PageCloseRo;
public RecognitionObject CookRo;
public RecognitionObject PageCloseMainRo;
public RecognitionObject CollectRo;
public RecognitionObject ReRo;
@@ -117,7 +118,24 @@ public class AutoSkipAssets : BaseAssets<AutoSkipAssets>
RegionOfInterest = new Rect(CaptureRect.Width - CaptureRect.Width / 8, 0, CaptureRect.Width / 8, CaptureRect.Height / 8),
DrawOnWindow = true
}.InitTemplate();
CookRo= new RecognitionObject
{
Name = "Cook",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoSkip", "cook.png"),
RegionOfInterest = new Rect(CaptureRect.Width / 15, 0, CaptureRect.Width / 14, CaptureRect.Height /14),
DrawOnWindow = true
}.InitTemplate();
PageCloseMainRo= new RecognitionObject
{
Name = "PageCloseMain",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoSkip", "page_close_main.png"),
RegionOfInterest = new Rect(0, 0, CaptureRect.Width / 25, CaptureRect.Height / 14),
DrawOnWindow = true
}.InitTemplate();
// 一键派遣
CollectRo = new RecognitionObject
{
@@ -41,25 +41,25 @@
"我带凯亚去没去过的地方玩吧"
],
"卡维结局1:未来蓝图": [
"一起去说服委托人吧",
"一起去说服刚刚的委托人吧",
"尝试一下新的风格"
],
"卡维结局2:契约达成": [
"一起去说服委托人吧",
"一起去说服刚刚的委托人吧",
"可以找其他商人筹款"
],
"卡维结局3:闲时小聚": [
"做些别的事转化心情",
"做些别的事转换心情",
"卡维为什么要当设计师呢",
"去找熟人问问"
],
"卡维结局4:群星之下": [
"做些别的事转化心情",
"做些别的事转换心情",
"卡维为什么要当设计师呢",
"还是先别管这个了"
],
"卡维结局5:第1堂课": [
"做些别的事转化心情",
"做些别的事转换心情",
"找份其他工作赚钱"
],
"莱依拉结局1:不可说之事": [
@@ -74,7 +74,7 @@
"莱依拉结局2:代价与回报": [
"虽然有些不靠谱",
"我陪你去找答案",
"仙灵应该不想苛责你"
"仙灵应该不只是想苛责你"
],
"莱依拉结局3:不愿重蹈覆辙": [
"虽然有些不靠谱",
@@ -3,6 +3,7 @@ using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoSkip.Assets;
using BetterGenshinImpact.GameTask.AutoSkip.Model;
using BetterGenshinImpact.GameTask.Common;
@@ -203,7 +204,7 @@ public partial class AutoSkipTrigger : ITaskTrigger
{
if (IsUseInteractionKey)
{
_postMessageSimulator?.KeyPressBackground(User32.VK.VK_F); // 注意这里不是交互键
_postMessageSimulator? .SimulateActionBackground(GIActions.PickUpOrInteract); // 注意这里不是交互键 NOTE By Ayu0K: 这里确实是交互键
}
else
{
@@ -3,6 +3,7 @@ using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoSkip.Model;
using BetterGenshinImpact.GameTask.Common;
@@ -113,7 +114,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
{
// 距离大于150米,先传送到最近的传送点
// J 打开任务 切换追踪打开地图 中心点就是任务点
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_J);
Simulation.SendInput.SimulateAction(GIActions.OpenQuestMenu);
Sleep(800, _ct);
// TODO 识别是否在任务界面
// 切换追踪
@@ -179,7 +180,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
private void StartTrackPoint()
{
// V键直接追踪
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_V);
Simulation.SendInput.SimulateAction(GIActions.QuestNavigation);
Sleep(3000, _ct);
var ra = CaptureToRectArea();
@@ -216,7 +217,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
Simulation.SendInput.Mouse.MoveMouseBy(-50, 0);
if (wDown)
{
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
wDown = false;
}
Debug.WriteLine("使追踪点位于俯视角上方");
@@ -242,7 +243,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
{
if (!wDown)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
wDown = true;
}
}
@@ -251,7 +252,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
{
if (wDown)
{
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
wDown = false;
}
// 识别距离
@@ -1,6 +1,7 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoTrackPath.Model;
using BetterGenshinImpact.GameTask.Common;
@@ -319,7 +320,10 @@ public class AutoTrackPathTask
var angle1 = GetCharacterOrientationAngle();
Simulation.SendInput.Mouse.MoveMouseBy(CharMovingUnit, 0);
Sleep(500);
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W).Sleep(100).KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Sleep(100);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
// Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W).Sleep(100).KeyUp(User32.VK.VK_W);
Sleep(1000);
var angle2 = GetCharacterOrientationAngle();
var angleOffset = angle2 - angle1;
@@ -1,4 +1,5 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.Model;
using System;
using Vanara.PInvoke;
@@ -15,7 +16,7 @@ public class MovementControl : Singleton<MovementControl>
if (!_wDown)
{
_wDown = true;
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
}
}
@@ -24,12 +25,12 @@ public class MovementControl : Singleton<MovementControl>
if (_wDown)
{
_wDown = false;
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
}
}
public void SpacePress()
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
Simulation.SendInput.SimulateAction(GIActions.Jump);
}
}
@@ -19,6 +19,10 @@ using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.Core.Script.Dependence;
using Microsoft.Diagnostics.Utilities;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
@@ -31,18 +35,111 @@ public class TpTask(CancellationToken ct)
private readonly Rect _captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
private readonly double _zoomOutMax1080PRatio = TaskContext.Instance().SystemInfo.ZoomOutMax1080PRatio;
public static double ReviveStatueOfTheSevenPointX = 2296.4;
public static double ReviveStatueOfTheSevenPointY = -824.4;
public static double currentZoomLevel = -1;
private static double ReviveStatueOfTheSevenPointX = 2296.4;
private static double ReviveStatueOfTheSevenPointY = -824.4;
private static int zoomOutButtonY = 654; // y-coordinate for zoom-out button
private static int zoomInButtonY = 428; // y-coordinate for zoom-in button
private static int zoomButtonX = 49; // x-coordinate for zoom button
private static int zoomStartY = 453; // y-coordinate for zoom start
private static int zoomEndY = 628; // y-coordinate for zoom end
private static bool _mapZoomEnabled = true;
private static int _mapZoomOutDistance = 1000;
private static int _mapZoomInDistance = 400;
private static int _stepIntervalMilliseconds = 20;
public static bool MapZoomEnabled
{
get => _mapZoomEnabled;
set
{
_mapZoomEnabled = value;
if(!value)
{
Logger.LogInformation("禁用了缩放功能,请自行调整合适的缩放,部分脚本可能会因为禁用缩放功能无法使用");
}
}
}
public static int MapZoomOutDistance
{
get => _mapZoomOutDistance;
set
{
if (value < 500 || value > 5000) // 自动设置合理范围
{
_mapZoomOutDistance = 1000;
}
if (value <= _mapZoomInDistance)
{
_mapZoomOutDistance = _mapZoomInDistance * 2;
}
_mapZoomOutDistance = value;
}
}
public static int MapZoomInDistance
{
get => _mapZoomInDistance;
set
{
if (value < 200 || value > 1000) // 自动设置合理范围
{
_mapZoomInDistance = 400;
}
if (value >= _mapZoomOutDistance)
{
_mapZoomInDistance = _mapZoomOutDistance / 2;
}
_mapZoomInDistance = value;
}
}
public static int StepIntervalMilliseconds
{
get => _stepIntervalMilliseconds;
set
{
if (value < 5 || value > 100)
{
_stepIntervalMilliseconds = 20;
}
_stepIntervalMilliseconds = value;
}
}
public async Task TpToStatueOfTheSeven()
{
await CheckInBigMapUi();
if (_mapZoomEnabled)
{
double currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
bool tempMapZoomEnable = _mapZoomEnabled;
_mapZoomEnabled = false; // 临时禁用缩放功能
if (currentZoomLevel > 4.5)
{
await AdjustMapZoomLevel(currentZoomLevel, 4.5);
}
else if (currentZoomLevel < 3)
{
await AdjustMapZoomLevel(currentZoomLevel, 3);
}
await Tp(ReviveStatueOfTheSevenPointX, ReviveStatueOfTheSevenPointY);
_mapZoomEnabled = tempMapZoomEnable;
}
else
{
await Tp(ReviveStatueOfTheSevenPointX, ReviveStatueOfTheSevenPointY);
}
}
/// <summary>
/// 通过大地图传送到指定坐标最近的传送点,然后移动到指定坐标
/// </summary>
/// <param name="tpX"></param>
/// <param name="tpY"></param>
/// <param name="force">强制以当前的tpX,tpY坐标进行自动传送</param>
/// <param name="initialZoomLevel">地图缩放等级</param>
public async Task<(double, double)> TpOnce(double tpX, double tpY, bool force = false, int initialZoomLevel = 4)
public async Task<(double, double)> TpOnce(double tpX, double tpY, bool force = false)
{
var (x, y) = (tpX, tpY);
string? country = null;
@@ -58,18 +155,22 @@ public class TpTask(CancellationToken ct)
// 计算坐标后点击
var bigMapInAllMapRect = GetBigMapRect();
currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
while (currentZoomLevel > 4.5)
if (_mapZoomEnabled)
{
await AdjustMapZoomLevel(true);
currentZoomLevel--;
Logger.LogInformation("当前缩放等级过大,调整为{currentZoomLevel}。", currentZoomLevel);
double zoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
if (zoomLevel > 4.5)
{
// 显示传送锚点和秘境的缩放等级
await AdjustMapZoomLevel(zoomLevel, 4.5);
Logger.LogInformation("当前缩放等级过大,调整为 {zoomLevel:0.000}", 4.5);
}
}
while (!IsPointInBigMapWindow(bigMapInAllMapRect, x, y) || currentZoomLevel > 2.5) // 左上角 350x400也属于禁止点击区域
while (!IsPointInBigMapWindow(bigMapInAllMapRect, x, y)) // 左上角 350x400也属于禁止点击区域
{
Debug.WriteLine($"({x},{y}) 不在 {bigMapInAllMapRect} 内,继续移动");
Logger.LogInformation("传送点不在当前大地图范围内,继续移动");
await MoveMapTo(x, y, maxMouseMove:400);
await MoveMapTo(x, y, maxMouseMove: 400);
await Delay(300, ct); // 等待地图移动完成
bigMapInAllMapRect = GetBigMapRect();
}
@@ -86,7 +187,7 @@ public class TpTask(CancellationToken ct)
await ClickTpPoint(CaptureToRectArea());
// 等待传送完成
for (var i = 0; i < 20; i++)
for (var i = 0; i < 50; i++)
{
await Delay(1200, ct);
using var ra3 = CaptureToRectArea();
@@ -151,13 +252,27 @@ public class TpTask(CancellationToken ct)
return (clickX, clickY);
}
public async Task<(double, double)> Tp(double tpX, double tpY, bool force = false)
private async Task CheckInBigMapUi()
{
// M 打开地图识别当前位置,中心点为当前位置
var ra1 = CaptureToRectArea();
if (!Bv.IsInBigMapUi(ra1))
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_M);
// 不在主界面的情况下,先回到主界面
if (!Bv.IsInMainUi(ra1))
{
for (int i = 0; i < 5; i++)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
await Delay(1000, ct);
ra1 = CaptureToRectArea();
if (Bv.IsInMainUi(ra1))
{
break;
}
}
}
Simulation.SendInput.SimulateAction(GIActions.OpenMap);
await Delay(1000, ct);
for (int i = 0; i < 3; i++)
{
@@ -167,13 +282,16 @@ public class TpTask(CancellationToken ct)
await Delay(500, ct);
}
}
}
}
}
public async Task<(double, double)> Tp(double tpX, double tpY, bool force = false)
{
await CheckInBigMapUi();
for (var i = 0; i < 3; i++)
{
try
{
return await TpOnce(tpX, tpY, force);
return await TpOnce(tpX, tpY, force: force);
}
catch (TpPointNotActivate e)
{
@@ -185,6 +303,7 @@ public class TpTask(CancellationToken ct)
}
catch (Exception e)
{
await CheckInBigMapUi();
Logger.LogError("传送失败,重试 {I} 次", i + 1);
Logger.LogDebug(e, "传送失败,重试 {I} 次", i + 1);
}
@@ -243,32 +362,47 @@ public class TpTask(CancellationToken ct)
totalMoveMouseX = Math.Abs(moveMouseX * xOffset / diffMapX);
totalMoveMouseY = Math.Abs(moveMouseY * yOffset / diffMapY);
double mouseDistance = Math.Sqrt(totalMoveMouseX * totalMoveMouseX + totalMoveMouseY * totalMoveMouseY);
// 调整地图缩放
// mapZoomLevel<5 才显示传送锚点和秘境;
// mapZoomLevel<3 是为了避免部分锚点过于接近导致选错锚点;
// 风龙废墟无法避免,但是目前没有风龙废墟的脚本吧。:)
// https://github.com/babalae/better-genshin-impact/issues/318
if (mouseDistance < tolerance && currentZoomLevel < 2.5)
if (_mapZoomEnabled)
{
Logger.LogInformation($"移动 {iteration} 次鼠标后,已经接近目标点,不再进一步调整。");
// 调整地图缩放
// mapZoomLevel<5 才显示传送锚点和秘境; mapZoomLevel>1.7 可以避免点错传送锚点
double currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
double oldZoomLevel = currentZoomLevel;
while (mouseDistance > MapZoomOutDistance || mouseDistance < MapZoomInDistance)
{
bool zoomOut = mouseDistance > MapZoomOutDistance;
bool zoomIn = mouseDistance < MapZoomInDistance;
if (zoomOut && currentZoomLevel < 4.0 || zoomIn && currentZoomLevel > 2.7)
{
await AdjustMapZoomLevel(zoomIn);
currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
totalMoveMouseX *= oldZoomLevel / currentZoomLevel;
totalMoveMouseY *= oldZoomLevel / currentZoomLevel;
mouseDistance *= oldZoomLevel / currentZoomLevel;
oldZoomLevel = currentZoomLevel;
}
else
{
double targetZoom = zoomIn ? 1.7 : 5.0;
// 考虑调整和识别误差,所以相差0.05就不再调整。
if (currentZoomLevel > 4.95 || currentZoomLevel < 1.75)
{
break;
}
await AdjustMapZoomLevel(currentZoomLevel, targetZoom);
break;
}
}
}
// 非常接近目标点,不再进一步调整
if (mouseDistance < tolerance)
{
Logger.LogInformation("移动 {I} 次鼠标后,已经接近目标点,不再移动地图。", iteration + 1);
break;
}
while (mouseDistance > 5 * tolerance && currentZoomLevel < 4)
{ // 缩小地图
await AdjustMapZoomLevel(false);
totalMoveMouseX *= (currentZoomLevel) / (currentZoomLevel + 1);
totalMoveMouseY *= (currentZoomLevel) / (currentZoomLevel + 1);
mouseDistance *= (currentZoomLevel) / (currentZoomLevel + 1);
currentZoomLevel++;
}
while (mouseDistance < 2 * tolerance && currentZoomLevel > 2)
{ // 放大地图
await AdjustMapZoomLevel(true);
totalMoveMouseX *= (currentZoomLevel) / (currentZoomLevel - 1);
totalMoveMouseY *= (currentZoomLevel) / (currentZoomLevel - 1);
mouseDistance *= (currentZoomLevel) / (currentZoomLevel - 1);
currentZoomLevel--;
}
// 单次移动最大距离为 maxMouseMove
moveMouseX = (int)Math.Min(totalMoveMouseX, maxMouseMove * totalMoveMouseX / mouseDistance) * Math.Sign(xOffset);
@@ -283,26 +417,48 @@ public class TpTask(CancellationToken ct)
}
}
/// <summary>
/// 点击并移动鼠标
/// </summary>
/// <param name="x1">鼠标初始位置x</param>
/// <param name="y1">鼠标初始位置y</param>
/// <param name="x2">鼠标移动后位置x</param>
/// <param name="y2">鼠标移动后位置y</param>
public async Task MouseClickAndMove(int x1, int y1, int x2, int y2)
{
GlobalMethod.MoveMouseTo(x1, y1);
await Delay(50, ct);
GlobalMethod.LeftButtonDown();
await Delay(50, ct);
GlobalMethod.MoveMouseTo(x2, y2);
await Delay(50, ct);
GlobalMethod.LeftButtonUp();
await Delay(50, ct);
}
/// <summary>
/// 调整地图缩放级别以加速移动
/// </summary>
/// <param name="zoomIn">是否放大地图</param>
/// <param name="zoomLevel">缩放等级:1-6,整数,随着数字变大地图越小,细节越少。</param>
public async Task AdjustMapZoomLevel(bool zoomIn)
{
if (zoomIn)
{
GameCaptureRegion.GameRegionClick((rect, scale) => (50 * scale, 430 * scale));
GameCaptureRegion.GameRegionClick((rect, scale) => (zoomButtonX * scale, zoomInButtonY * scale));
}
else
{
GameCaptureRegion.GameRegionClick((rect, scale) => (50 * scale, 650 * scale));
GameCaptureRegion.GameRegionClick((rect, scale) => (zoomButtonX * scale, zoomOutButtonY * scale));
}
await Delay(50, ct);
}
[Obsolete]
/// <summary>
/// 调整地图的缩放等级(整数缩放级别)。
/// </summary>
/// <param name="zoomLevel">目标等级:1-6。整数。随着数字变大地图越小,细节越少。</param>
public async Task AdjustMapZoomLevel(int zoomLevel)
{
for (int i = 0; i < 5; i++)
@@ -317,15 +473,26 @@ public class TpTask(CancellationToken ct)
}
}
public async Task MouseMoveMap(int pixelDeltaX, int pixelDeltaY, int steps = 10, int stepIntervalMilliseconds = 10)
/// <summary>
/// 调整地图的缩放级别(支持浮点数精度)。
/// </summary>
/// <param name="zoomLevel">当前缩放等级:1.0-6.0,浮点数。</param>
/// <param name="targetZoomLevel">目标缩放等级:1.0-6.0,浮点数。</param>
public async Task AdjustMapZoomLevel(double zoomLevel, double targetZoomLevel)
{
// Logger.LogInformation("调整地图缩放等级:{zoomLevel:0.000} -> {targetZoomLevel:0.000}", zoomLevel, targetZoomLevel);
int initialY = (int)(zoomStartY + (zoomEndY - zoomStartY) * (zoomLevel - 1) / 5d);
int targetY = (int)(zoomStartY + (zoomEndY - zoomStartY) * (targetZoomLevel - 1) / 5d);
await MouseClickAndMove(zoomButtonX, initialY, zoomButtonX, targetY);
}
public async Task MouseMoveMap(int pixelDeltaX, int pixelDeltaY, int steps = 10)
{
// 确保不影响总移动距离
int totalX = 0;
int totalY = 0;
// 梯形缩放因子
double scaleFactor = 0.75;
// 计算每一步的位移,从steps/2逐渐减小到0
int[] stepX = new int[steps];
int[] stepY = new int[steps];
@@ -352,13 +519,13 @@ public class TpTask(CancellationToken ct)
(rect.Width / 2d + Random.Shared.Next(-rect.Width / 6, rect.Width / 6),
rect.Height / 2d + Random.Shared.Next(-rect.Height / 6, rect.Height / 6)));
Simulation.SendInput.Mouse.LeftButtonDown();
GlobalMethod.LeftButtonDown();
for (var i = 0; i < steps; i++)
{
Simulation.SendInput.Mouse.MoveMouseBy(stepX[i], stepY[i]);
await Delay(stepIntervalMilliseconds, ct);
GlobalMethod.MoveMouseBy(stepX[i], stepY[i]);
await Delay(StepIntervalMilliseconds, ct);
}
Simulation.SendInput.Mouse.LeftButtonUp();
GlobalMethod.LeftButtonUp();
}
@@ -459,8 +626,6 @@ public class TpTask(CancellationToken ct)
country = tpPosition.Country;
}
}
// todo: 识别当前国家
return (recentX, recentY, country);
}
@@ -530,11 +695,13 @@ public class TpTask(CancellationToken ct)
public async Task Tp(string name)
{
// 通过大地图传送到指定传送点
await Delay(500, ct);
}
public async Task TpByF1(string name)
{
// 传送到指定传送点
await Delay(500, ct);
}
public async Task ClickTpPoint(ImageRegion imageRegion)
@@ -16,6 +16,7 @@ using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Simulator.Extensions;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.User32;
@@ -30,7 +31,7 @@ public partial class AutoWoodTask : ISoloTask
{
public string Name => "自动伐木";
private readonly AutoWoodAssets _assets;
private AutoWoodAssets _assets;
private bool _first = true;
@@ -38,7 +39,7 @@ public partial class AutoWoodTask : ISoloTask
private readonly Login3rdParty _login3rdParty;
private VK _zKey = VK.VK_Z;
// private VK _zKey = VK.VK_Z;
private readonly WoodTaskParam _taskParam;
@@ -49,12 +50,13 @@ public partial class AutoWoodTask : ISoloTask
this._taskParam = taskParam;
_login3rdParty = new();
AutoWoodAssets.DestroyInstance();
_assets = AutoWoodAssets.Instance;
_printer = new WoodStatisticsPrinter(_assets);
}
public Task Start(CancellationToken ct)
{
_assets = AutoWoodAssets.Instance;
var runTimeWatch = new Stopwatch();
_ct = ct;
_printer.Ct = _ct;
@@ -70,20 +72,20 @@ public partial class AutoWoodTask : ISoloTask
Logger.LogInformation("自动伐木启用B服模式");
}
SettingsContainer settingsContainer = new();
if (settingsContainer.OverrideController?.KeyboardMap?.ActionElementMap.Where(item => item.ActionId == ActionId.Gadget).FirstOrDefault()?.ElementIdentifierId is ElementIdentifierId key)
{
if (key != ElementIdentifierId.Z)
{
_zKey = key.ToVK();
Logger.LogInformation($"自动伐木检测到用户改键 {ElementIdentifierId.Z.ToName()} 改为 {key.ToName()}");
if (key == ElementIdentifierId.LeftShift || key == ElementIdentifierId.RightShift)
{
Logger.LogInformation($"用户改键 {key.ToName()} 可能不受模拟支持,若使用正常则忽略");
}
}
}
// SettingsContainer settingsContainer = new();
//
// if (settingsContainer.OverrideController?.KeyboardMap?.ActionElementMap.Where(item => item.ActionId == ActionId.Gadget).FirstOrDefault()?.ElementIdentifierId is ElementIdentifierId key)
// {
// if (key != ElementIdentifierId.Z)
// {
// _zKey = key.ToVK();
// Logger.LogInformation($"自动伐木检测到用户改键 {ElementIdentifierId.Z.ToName()} 改为 {key.ToName()}");
// if (key == ElementIdentifierId.LeftShift || key == ElementIdentifierId.RightShift)
// {
// Logger.LogInformation($"用户改键 {key.ToName()} 可能不受模拟支持,若使用正常则忽略");
// }
// }
// }
SystemControl.ActivateWindow();
// 伐木开始计时
@@ -168,6 +170,7 @@ public partial class AutoWoodTask : ISoloTask
TaskContext.Instance().Config.AutoWoodConfig.WoodCountOcrEnabled = false;
throw new NormalEndException("首次伐木就未识别到木材数据,已经自动关闭【OCR识别并累计木材数】的功能,请重新启动【自动伐木】功能!");
}
return;
}
@@ -210,6 +213,7 @@ public partial class AutoWoodTask : ISoloTask
return _firstWoodOcrText;
}
}
stopwatch.Stop(); // 停止计时
_firstWoodOcrText = FindBestOcrResult(firstOcrResultList);
return _firstWoodOcrText;
@@ -234,6 +238,7 @@ public partial class AutoWoodTask : ISoloTask
return !string.IsNullOrEmpty(recognizedText) &&
recognizedText.Contains("获得");
}
return !string.IsNullOrEmpty(recognizedText) &&
recognizedText.Contains("获得") &&
(recognizedText.Contains('×') || recognizedText.Contains('x'));
@@ -291,6 +296,7 @@ public partial class AutoWoodTask : ISoloTask
Logger.LogWarning("未知的木材名:{woodName},数量{Cnt}", materialName, quantity);
return;
}
WoodTotalDict.AddOrUpdate(
key: materialName,
addValue: quantity,
@@ -334,6 +340,7 @@ public partial class AutoWoodTask : ISoloTask
isFound = false;
continue;
}
var materialName = match.Groups[1].Value.Trim();
Debug.WriteLine($"第一次获取的木材名称:{materialName}");
if (!ExistWoods.Contains(materialName))
@@ -417,14 +424,14 @@ public partial class AutoWoodTask : ISoloTask
throw new NormalEndException("请先装备小道具「王树瑞佑」!");
#else
System.Threading.Thread.Sleep(2000);
Simulation.SendInput.Keyboard.KeyPress(_zKey);
Simulation.SendInput.SimulateAction(GIActions.QuickUseGadget);
Debug.WriteLine("[AutoWood] Z");
_first = false;
#endif
}
else
{
Simulation.SendInput.Keyboard.KeyPress(_zKey);
Simulation.SendInput.SimulateAction(GIActions.QuickUseGadget);
Debug.WriteLine("[AutoWood] Z");
_first = false;
}
@@ -445,7 +452,7 @@ public partial class AutoWoodTask : ISoloTask
#endif
}
Simulation.SendInput.Keyboard.KeyPress(_zKey);
Simulation.SendInput.SimulateAction(GIActions.QuickUseGadget);
Debug.WriteLine("[AutoWood] Z");
Sleep(500, _ct);
}, TimeSpan.FromSeconds(1), 120);
@@ -542,4 +549,4 @@ public partial class AutoWoodTask : ISoloTask
throw new RetryException("未检测进入游戏界面");
}
}
}
}
@@ -10,6 +10,7 @@ using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Simulator.Extensions;
namespace BetterGenshinImpact.GameTask.Common.Job;
@@ -25,7 +26,7 @@ public class ArtifactSalvageTask
await _returnMainUiTask.Start(ct);
// B键打开背包
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_B);
Simulation.SendInput.SimulateAction(GIActions.OpenInventory);
await Delay(1000, ct);
var openBagSuccess = await NewRetry.WaitForAction(() =>
@@ -51,7 +52,7 @@ public class ArtifactSalvageTask
if (Bv.IsInMainUi(ra))
{
Debug.WriteLine("背包打开失败,再次尝试打开背包");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_B);
Simulation.SendInput.SimulateAction(GIActions.OpenInventory);
}
return false;
@@ -2,6 +2,7 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Model.Area;
using Microsoft.Extensions.Logging;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -14,22 +15,19 @@ public class BlessingOfTheWelkinMoonTask
{
public string Name => "自动点击空月祝福";
private DateTime _lastRunTime = DateTime.MinValue;
private bool _retry = false;
public async Task Start(CancellationToken ct)
{
try
{
// 4点分界线触发一次
if ((DateTime.Now.Hour == 4 && _lastRunTime.Date.Hour == 3) || _retry)
// 4点全程触发
if (DateTime.Now.Hour == 4)
{
_retry = true;
using var ra = CaptureToRectArea();
if (Bv.IsInBlessingOfTheWelkinMoon(ra))
{
Logger.LogInformation("检测到空月祝福界面,自动点击");
GameCaptureRegion.GameRegion1080PPosMove(100,100);
TaskContext.Instance().PostMessageSimulator.LeftButtonClickBackground();
await Delay(5000, ct);
@@ -49,8 +47,6 @@ public class BlessingOfTheWelkinMoonTask
TaskContext.Instance().PostMessageSimulator.LeftButtonClickBackground();
}
}
_lastRunTime = DateTime.Now;
}
catch (Exception e)
{
@@ -63,7 +63,7 @@ public partial class ChooseTalkOptionTask
{
if (isOrange)
{
region.DeriveCrop(optionRa.ToRect()).SrcMat.SaveImage(Global.Absolute($"log\\t{optionRa.Text}.png"));
// region.DeriveCrop(optionRa.ToRect()).SrcMat.SaveImage(Global.Absolute($"log\\t{optionRa.Text}.png"));
if (!IsOrangeOption(region.DeriveCrop(optionRa.ToRect()).SrcMat))
{
return TalkOptionRes.FoundButNotOrange;
@@ -3,6 +3,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers.Extensions;
@@ -37,7 +38,7 @@ public class ClaimBattlePassRewardsTask
await _returnMainUiTask.Start(ct);
await Delay(200, ct);
TaskContext.Instance().PostMessageSimulator.KeyPress(User32.VK.VK_F4); // F4 开纪行
TaskContext.Instance().PostMessageSimulator.SimulateAction(GIActions.OpenBattlePassScreen); // F4 开纪行
// 领取战令1
await Delay(500, ct);
@@ -4,7 +4,9 @@ using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Model.Area;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -37,12 +39,13 @@ public class ClaimEncounterPointsRewardsTask
await Delay(200, ct);
TaskContext.Instance().PostMessageSimulator.KeyPress(User32.VK.VK_F1); // F1 开书
TaskContext.Instance().PostMessageSimulator.SimulateAction(GIActions.OpenAdventurerHandbook); // F1 开书
await Delay(1000, ct);
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var earlyClaim = false; // 无需点击委托直接领取
// 找委托按钮
var f1Success = await NewRetry.WaitForAction(() =>
{
@@ -54,6 +57,12 @@ public class ClaimEncounterPointsRewardsTask
if (wt != null)
{
if (ClickClaimBtn(CaptureToRectArea()))
{
earlyClaim = true;
return true;
}
wt.Click();
return true;
}
@@ -67,24 +76,44 @@ public class ClaimEncounterPointsRewardsTask
return;
}
if (earlyClaim)
{
// 已经领取过
await Delay(1000, ct);
// TODO 截图并通知
return;
}
await Delay(1000, ct);
// 领取
using var ra2 = CaptureToRectArea();
var claimBtn = ra2.Find(ElementAssets.Instance.BtnClaimEncounterPointsRewards);
if (claimBtn.IsExist())
if (ClickClaimBtn(CaptureToRectArea()))
{
claimBtn.Click();
Logger.LogInformation("{F}领取长效历练点奖励", "历练点:");
await Delay(1000, ct);
// TODO 截图并通知
}
else
{
Logger.LogInformation("{F}未找到领取历练点奖励按钮", "历练点:");
}
// 关闭
await _returnMainUiTask.Start(ct);
}
private static bool ClickClaimBtn(ImageRegion ra2)
{
var claimBtn = ra2.Find(ElementAssets.Instance.BtnClaimEncounterPointsRewards);
if (claimBtn.IsExist())
{
claimBtn.Click();
Logger.LogInformation("{F}领取长效历练点奖励", "历练点:");
return true;
}
else
{
Logger.LogInformation("{F}未找到领取历练点奖励按钮", "历练点:");
return false;
}
}
}
@@ -4,6 +4,7 @@ using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
@@ -37,7 +38,7 @@ public class ClaimMailRewardsTask
await Delay(200, ct);
TaskContext.Instance().PostMessageSimulator.KeyPress(User32.VK.VK_ESCAPE); // ESC
TaskContext.Instance().PostMessageSimulator.SimulateAction(GIActions.OpenPaimonMenu); // ESC
await Delay(1300, ct);
@@ -36,6 +36,9 @@ public class GoToAdventurersGuildTask
{
await new SwitchPartyTask().Start(dailyRewardPartyName, ct);
}
// F1领取奖励
await new ClaimEncounterPointsRewardsTask().Start(ct);
await DoOnce(country, ct);
break;
@@ -69,7 +72,7 @@ public class GoToAdventurersGuildTask
if (res == TalkOptionRes.FoundAndClick)
{
Logger.LogInformation("▶ {Text}", "领取『每日委托』奖励!");
await Delay(200, ct);
await Delay(500, ct);
await _chooseTalkOptionTask.SelectLastOptionUntilEnd(ct, null, 3); // 点几下
await Bv.WaitUntilFound(ElementAssets.Instance.PaimonMenuRo, ct);
await Delay(500, ct);
@@ -77,7 +80,7 @@ public class GoToAdventurersGuildTask
await new ReturnMainUiTask().Start(ct);
// 结束后重新打开
await Delay(200, ct);
await Delay(1000, ct);
var ra = CaptureToRectArea();
if (!Bv.FindFAndPress(ra, "凯瑟琳"))
{
@@ -29,8 +29,6 @@ public class GoToCraftingBenchTask
try
{
await DoOnce(country, ct);
// 合成完毕后领取奖励
await new ClaimEncounterPointsRewardsTask().Start(ct);
break;
}
catch (Exception e)
@@ -100,7 +98,8 @@ public class GoToCraftingBenchTask
PartyConfig = new PathingPartyConfig
{
Enabled = true,
AutoSkipEnabled = true
AutoSkipEnabled = true,
AutoRunEnabled = country != "枫丹" ,
},
EndAction = region => Bv.FindFAndPress(region, "合成")
};
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more