lie_watcher.py 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158
  1. # -*- coding: utf-8 -*-
  2. """
  3. 冒险岛 · 谎言探测仪 提醒工具
  4. ================================================
  5. 只做一件事:盯着游戏画面,一旦「谎言探测仪」对话框出现,
  6. 立刻响警报 + 弹红窗 + 把游戏窗口切到最前,把你叫回电脑前。
  7. 不读内存、不注入、不模拟鼠标键盘,只截屏看画面。
  8. 用法:
  9. python lie_watcher.py 开始监控(带状态小窗)
  10. python lie_watcher.py --no-gui 只要声音/弹窗,不显示状态窗
  11. python lie_watcher.py demo 屏幕上弹一个假的测谎窗口,测试用
  12. python lie_watcher.py check a.png 对图片跑识别,看分数、调阈值
  13. python lie_watcher.py once 对当前屏幕跑一次识别
  14. python lie_watcher.py learn 框选一小块存成模板(适配你的分辨率)
  15. python lie_watcher.py list 列出屏幕上的窗口标题(找游戏窗口名用)
  16. """
  17. import argparse
  18. import ctypes
  19. import json
  20. import os
  21. import queue
  22. import re
  23. import shutil
  24. import sys
  25. import threading
  26. import time
  27. import wave
  28. from ctypes import wintypes
  29. from pathlib import Path
  30. from typing import Dict, List, Optional, Tuple
  31. import cv2
  32. import numpy as np
  33. # ---------------------------------------------------------------- 路径
  34. def _app_dir() -> Path:
  35. """配置/模板/日志放哪儿。
  36. 源码运行时放脚本旁边;打包成 exe 后放 exe 旁边——
  37. 这样别人拿到 exe 也能直接改 config.json、能 learn 新模板。
  38. """
  39. if getattr(sys, "frozen", False):
  40. return Path(sys.executable).resolve().parent
  41. return Path(__file__).resolve().parent
  42. APP_DIR = _app_dir()
  43. # exe = onefile 时,打包进去的模板/演示图会被解到临时目录,这里记住它在哪
  44. BUNDLE_DIR = Path(getattr(sys, "_MEIPASS", APP_DIR))
  45. TEMPLATE_DIR = APP_DIR / "templates"
  46. HUD_DIR = TEMPLATE_DIR / "hud"
  47. ASSET_DIR = APP_DIR / "assets"
  48. LOG_DIR = APP_DIR / "logs"
  49. CONFIG_PATH = APP_DIR / "config.json"
  50. APP_NAME = "测谎仪提醒"
  51. # ---------------------------------------------------------------- 默认配置
  52. DEFAULT_CONFIG = {
  53. # 游戏窗口标题:包含其中任意一个就算(不区分大小写)
  54. "game_window_titles": ["冒险岛怀旧服", "冒险岛", "MapleStory"],
  55. # game_window = 只截游戏窗口那块的画面(快、干扰少);screen = 整屏
  56. "capture": "game_window",
  57. # 模板缩放档位。1.0 = 和模板原尺寸一致;1.25 = 你的画面比模板大 25%
  58. # 每多一档就多一份耗时,先只查 1.0;档位不对时程序会自己扫一遍宽范围再记住
  59. "scales": [1.0],
  60. # 自动适应:档位不对时自己扫下面这些,扫到就把结果写进 scales(下次直接按它查)
  61. "auto_scale": True,
  62. # 隔一段时间扫一遍这些档位,防止你的画面缩放跟模板差太多
  63. # 覆盖常见窗口/DPI:约 0.65x(小窗/高 DPI)到 1.50x(大分辨率放大)
  64. "scales_wide": [
  65. 1.0, 0.95, 1.05, 0.9, 1.1, 0.85, 1.15, 0.8, 1.2,
  66. 0.75, 1.25, 0.7, 1.35, 0.65, 1.5,
  67. ],
  68. # 多少帧做一次宽范围扫描(帧数越少越保险,代价是更费 CPU)
  69. "rescan_every": 40,
  70. # 用底部 HP 标签推算 UI 缩放(多分辨率时比盲扫更准、更快)
  71. "scale_from_hud": True,
  72. # 粗查时把画面缩小几倍跑(2 = 半分辨率,快 4 倍);1 = 不缩,最准但最慢
  73. "scale_down": 2.0,
  74. # 相似度阈值,超过就算出现。低了误报,高了漏报
  75. # 0.75:挡掉聊天区「有点像」的误报;真测谎窗通常 0.90+
  76. "threshold": 0.75,
  77. # 至少要几个不同模板同时过阈值才算真的出现(2 能挡掉只有标题像的误报)
  78. "min_hits": 2,
  79. # 单独一个模板高到这个分数也直接认(防止某天字变了、只剩一块认得出时漏报)
  80. # 仍要求附近还有第二块「像」的(见 layout),避免标题撞到聊天字
  81. "strong_threshold": 0.92,
  82. # 命中模板必须挤在测谎对话框那么大的一块区域里(聊天框散落匹配直接否掉)
  83. "require_layout": True,
  84. # 只有 2 个模板过线时,平均分还得够高才认(真对话框通常远高于此)
  85. "pair_avg_threshold": 0.82,
  86. # 连续几帧都确认才报警(1=立刻报;2=挡一帧噪声/闪一下的误报)
  87. "confirm_frames": 2,
  88. # 每秒最多检查几次(想省 CPU 就调小,3 就算很够用了)
  89. "max_fps": 5,
  90. # 对话框一直在时,每隔多少秒再叫一次
  91. "alert_repeat_seconds": 15,
  92. "alert": {
  93. "sound": True, # 警报音
  94. "sound_seconds": 10, # 每次响多久
  95. "volume": 0.9, # 0.1 ~ 1.0
  96. "voice": False, # 语音播报(要系统有中文语音,没有会自动跳过)
  97. "popup": True, # 屏幕上的红色提醒窗
  98. "popup_seconds": 12, # 红色提醒窗自动关闭时间
  99. "bring_to_front": True, # 把游戏窗口切到最前
  100. "save_snapshot": True, # 触发时存一张现场截图到 logs/(方便看误报)
  101. "snooze_seconds": 60, # 点掉提醒窗后,多少秒内不再吵
  102. },
  103. # ---- 画面底部那条 HP / MP / EXP(读它才能做低血提醒和经验统计)
  104. "hud": {
  105. "enabled": True, # 关掉就完全不读血蓝,只做测谎
  106. },
  107. # ---- 血量/蓝量过低提醒(比测谎轻,不会盖住测谎的红窗)
  108. "hp_alert": {
  109. "enabled": True, # 总开关
  110. "low_pct": 30, # 低于这个百分比就提醒
  111. "recover_pct": 35, # 回到这个百分比以上才算脱险,下次掉下来才会再提醒
  112. "repeat_seconds": 30, # 一直低着不动,隔这么多秒再叫一次
  113. "mp_enabled": True, # 蓝量也提醒
  114. "mp_low_pct": 10, # 蓝量低于这个百分比提醒
  115. "mp_recover_pct": 15,
  116. "sound": True, # 短促两声,不是测谎那种连响
  117. "volume": 0.45,
  118. "popup": True, # 右上角小提示条
  119. "popup_seconds": 6,
  120. },
  121. # ---- 经验统计
  122. "exp": {
  123. "enabled": False, # 打开后会记录经验、算 1H 速率、画走势
  124. "sample_seconds": 10, # 每多少秒记一次
  125. "window_minutes": 5, # 「实时 1H」用最近多少分钟的样本算
  126. "save_csv": True, # 存 logs/exp_日期.csv,可以用 Excel 打开
  127. "window": True, # 打开经验统计小窗
  128. },
  129. # 状态小窗是否总在最前
  130. "status_on_top": False,
  131. # ---- 测谎出现后:YOLO+ByteTrack 跟踪 + Interception 鼠标跟红准星
  132. "aim_assist": {
  133. "enabled": True, # 报警后自动开瞄准
  134. "backend": "bytetrack", # bytetrack | deepsort
  135. "weights": "models/best.pt", # 相对 ch/ 目录
  136. "conf": 0.25,
  137. "imgsz": 640,
  138. "duration_seconds": 25, # 一次最长跟多久
  139. "miss_stop_frames": 45, # 连续丢目标这么多帧就停
  140. "gain": 1.0, # 跟手增益,1=尽量贴准星
  141. "deadzone": 1.5, # 像素死区,小于此不挪
  142. "min_conf": 0.20, # 低于此置信度当丢目标
  143. "show_overlay": False, # 调试预览窗(会抢焦点,挂机别开)
  144. "on_manual_test": False, # 点「测试」要不要也开瞄准
  145. },
  146. }
  147. # ---------------------------------------------------------------- 小工具
  148. def setup_console() -> None:
  149. """让中文在 cmd / PowerShell 里正常显示。"""
  150. try:
  151. ctypes.windll.kernel32.SetConsoleOutputCP(65001)
  152. except Exception:
  153. pass
  154. for stream in (sys.stdout, sys.stderr):
  155. try:
  156. if stream is not None:
  157. stream.reconfigure(encoding="utf-8", errors="replace")
  158. except Exception:
  159. pass
  160. def attach_console() -> None:
  161. """打包成无控制台的 exe 后:从 cmd / PowerShell 启动就借它的控制台打印,
  162. 双击启动没有控制台,那就安静跑(消息还是会写进 logs\\lie_watcher.log)。"""
  163. if sys.stdout is not None:
  164. return
  165. try:
  166. if not ctypes.windll.kernel32.AttachConsole(-1): # ATTACH_PARENT_PROCESS
  167. return
  168. sys.stdout = open("CONOUT$", "w", encoding="utf-8", errors="replace")
  169. sys.stderr = open("CONOUT$", "w", encoding="utf-8", errors="replace")
  170. except Exception:
  171. pass
  172. def seed_bundled_data() -> None:
  173. """exe 第一次运行时,把打包进去的模板/演示图/YOLO 权重复制到 exe 旁边。
  174. 之后所有东西都在 exe 旁边:config.json 能改、learn 出的新模板存得下、
  175. 报警截图写在 logs\\ 里,整个文件夹拷给别人也是一份完整可用的。
  176. ch/models 也会放出一份,方便以后只换权重不用重打包。
  177. """
  178. if not getattr(sys, "frozen", False):
  179. return
  180. for sub in ("templates", "assets", "ch/models", "第三方"):
  181. src = BUNDLE_DIR / sub
  182. if not src.exists():
  183. continue
  184. try:
  185. if src.is_file():
  186. target = APP_DIR / sub
  187. if not target.exists():
  188. target.parent.mkdir(parents=True, exist_ok=True)
  189. shutil.copy2(str(src), str(target))
  190. continue
  191. for item in src.rglob("*"): # 连 templates\hud\ 这种子目录一起
  192. target = APP_DIR / sub / item.relative_to(src)
  193. if item.is_dir():
  194. target.mkdir(parents=True, exist_ok=True)
  195. elif not target.exists():
  196. target.parent.mkdir(parents=True, exist_ok=True)
  197. shutil.copy2(str(item), str(target))
  198. except OSError:
  199. pass
  200. def enable_dpi_awareness() -> None:
  201. """不声明 DPI 感知的话,1920x1080 在 125% 缩放下会被系统骗成 1536x864,坐标全错。"""
  202. try:
  203. ctypes.windll.shcore.SetProcessDpiAwareness(2) # 每显示器 v2
  204. return
  205. except Exception:
  206. pass
  207. try:
  208. ctypes.windll.user32.SetProcessDPIAware()
  209. except Exception:
  210. pass
  211. _log_lock = threading.Lock()
  212. def log(msg: str) -> None:
  213. line = "[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg)
  214. with _log_lock:
  215. try:
  216. if sys.stdout is not None:
  217. print(line, flush=True)
  218. except Exception:
  219. pass
  220. try:
  221. LOG_DIR.mkdir(parents=True, exist_ok=True)
  222. path = LOG_DIR / "lie_watcher.log"
  223. if path.exists() and path.stat().st_size > 2 * 1024 * 1024:
  224. path.replace(LOG_DIR / "lie_watcher.old.log")
  225. with open(path, "a", encoding="utf-8") as fh:
  226. fh.write(line + "\n")
  227. except Exception:
  228. pass
  229. def imread_gray(path) -> Optional[np.ndarray]:
  230. """读图。cv2.imread 不支持中文路径,所以走 imdecode。"""
  231. try:
  232. buf = np.fromfile(str(path), dtype=np.uint8)
  233. if buf.size == 0:
  234. return None
  235. return cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
  236. except Exception:
  237. return None
  238. def imwrite(path, img) -> bool:
  239. """存图。同样为了中文路径。"""
  240. try:
  241. ok, buf = cv2.imencode(".png", img)
  242. if not ok:
  243. return False
  244. buf.tofile(str(path))
  245. return True
  246. except Exception:
  247. return False
  248. # ---------------------------------------------------------------- GDI 抓屏
  249. SRCCOPY = 0x00CC0020
  250. CAPTUREBLT = 0x40000000
  251. user32 = ctypes.windll.user32
  252. gdi32 = ctypes.windll.gdi32
  253. class BITMAPINFOHEADER(ctypes.Structure):
  254. _fields_ = [
  255. ("biSize", wintypes.DWORD), ("biWidth", wintypes.LONG),
  256. ("biHeight", wintypes.LONG), ("biPlanes", wintypes.WORD),
  257. ("biBitCount", wintypes.WORD), ("biCompression", wintypes.DWORD),
  258. ("biSizeImage", wintypes.DWORD), ("biXPelsPerMeter", wintypes.LONG),
  259. ("biYPelsPerMeter", wintypes.LONG), ("biClrUsed", wintypes.DWORD),
  260. ("biClrImportant", wintypes.DWORD),
  261. ]
  262. class BITMAPINFO(ctypes.Structure):
  263. _fields_ = [("bmiHeader", BITMAPINFOHEADER), ("bmiColors", wintypes.DWORD * 3)]
  264. class ScreenGrabber:
  265. """ctypes 直接调 GDI 抓屏,不依赖 mss / Pillow。
  266. 复用同一个内存 DC 和缓冲区,1920x1080 一帧约 35~55ms。
  267. """
  268. def __init__(self):
  269. self._w = 0
  270. self._h = 0
  271. self._hdc = None
  272. self._mdc = None
  273. self._bmp = None
  274. self._buf = None
  275. self._bi = None
  276. def _release(self) -> None:
  277. try:
  278. if self._mdc and self._bmp:
  279. gdi32.SelectObject(self._mdc, self._bmp)
  280. if self._bmp:
  281. gdi32.DeleteObject(self._bmp)
  282. if self._mdc:
  283. gdi32.DeleteDC(self._mdc)
  284. if self._hdc:
  285. user32.ReleaseDC(None, self._hdc)
  286. except Exception:
  287. pass
  288. self._hdc = self._mdc = self._bmp = self._buf = self._bi = None
  289. self._w = self._h = 0
  290. def _prepare(self, w: int, h: int) -> None:
  291. self._release()
  292. self._hdc = user32.GetDC(None)
  293. self._mdc = gdi32.CreateCompatibleDC(self._hdc)
  294. self._bmp = gdi32.CreateCompatibleBitmap(self._hdc, w, h)
  295. gdi32.SelectObject(self._mdc, self._bmp)
  296. self._buf = ctypes.create_string_buffer(w * h * 4)
  297. bi = BITMAPINFO()
  298. bi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
  299. bi.bmiHeader.biWidth = w
  300. bi.bmiHeader.biHeight = -h # 负高度 = 自上而下
  301. bi.bmiHeader.biPlanes = 1
  302. bi.bmiHeader.biBitCount = 32
  303. bi.bmiHeader.biCompression = 0 # BI_RGB
  304. self._bi = bi
  305. self._w, self._h = w, h
  306. def grab_gray(self, x: int, y: int, w: int, h: int) -> Optional[np.ndarray]:
  307. w, h = max(1, int(w)), max(1, int(h))
  308. if (w, h) != (self._w, self._h):
  309. self._prepare(w, h)
  310. try:
  311. gdi32.BitBlt(self._mdc, 0, 0, w, h, self._hdc, int(x), int(y),
  312. SRCCOPY | CAPTUREBLT)
  313. gdi32.GetDIBits(self._mdc, self._bmp, 0, h, self._buf,
  314. ctypes.byref(self._bi), 0)
  315. arr = np.frombuffer(self._buf, dtype=np.uint8, count=w * h * 4)
  316. arr = arr.reshape(h, w, 4)
  317. return cv2.cvtColor(arr, cv2.COLOR_BGRA2GRAY)
  318. except Exception:
  319. return None
  320. def grab_bgr(self, x: int, y: int, w: int, h: int) -> Optional[np.ndarray]:
  321. gray = self.grab_gray(x, y, w, h)
  322. if gray is None:
  323. return None
  324. return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
  325. def close(self) -> None:
  326. self._release()
  327. # ---------------------------------------------------------------- 窗口
  328. def virtual_screen() -> Tuple[int, int, int, int]:
  329. return (user32.GetSystemMetrics(76), user32.GetSystemMetrics(77),
  330. user32.GetSystemMetrics(78), user32.GetSystemMetrics(79))
  331. def clamp_region(region: Tuple[int, int, int, int]) -> Tuple[int, int, int, int]:
  332. x, y, w, h = region
  333. vx, vy, vw, vh = virtual_screen()
  334. x2, y2 = min(x + w, vx + vw), min(y + h, vy + vh)
  335. x, y = max(x, vx), max(y, vy)
  336. return (int(x), int(y), int(max(1, x2 - x)), int(max(1, y2 - y)))
  337. def iter_windows() -> List[Tuple[int, str]]:
  338. found: List[Tuple[int, str]] = []
  339. proto = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
  340. def _cb(hwnd, _lparam):
  341. try:
  342. if user32.IsWindowVisible(hwnd):
  343. n = user32.GetWindowTextLengthW(hwnd)
  344. if n > 0:
  345. buf = ctypes.create_unicode_buffer(n + 1)
  346. user32.GetWindowTextW(hwnd, buf, n + 1)
  347. found.append((hwnd, buf.value))
  348. except Exception:
  349. pass
  350. return True
  351. user32.EnumWindows(proto(_cb), 0)
  352. return found
  353. def client_rect(hwnd: int) -> Tuple[int, int, int, int]:
  354. pt = wintypes.POINT(0, 0)
  355. user32.ClientToScreen(hwnd, ctypes.byref(pt))
  356. rc = wintypes.RECT()
  357. user32.GetClientRect(hwnd, ctypes.byref(rc))
  358. return (pt.x, pt.y, rc.right - rc.left, rc.bottom - rc.top)
  359. def find_game_window(titles: List[str]) -> Tuple[int, Optional[Tuple[int, int, int, int]]]:
  360. """按标题找游戏窗口,返回 (hwnd, 客户区屏幕矩形)。找不到返回 (0, None)。
  361. 优先级:标题完全一样 > 标题以它开头(越短越像)> 标题里包含它。
  362. 这一步很要紧:浏览器标签、聊天窗口的标题里也常有"冒险岛"
  363. (比如本工具的聊天窗口叫"冒险岛测谎界面提醒工具"),
  364. 只按"包含"来找会抓错窗口;只有一档"包含"命中时干脆不认,退回整屏监控。
  365. """
  366. keys = [k.strip().lower() for k in titles if k and k.strip()]
  367. best = None # (score, -len(title), area, hwnd, rect)
  368. for hwnd, title in iter_windows():
  369. if not title:
  370. continue
  371. low = title.strip().lower()
  372. score = 0
  373. for k in keys:
  374. if low == k:
  375. score = max(score, 3)
  376. elif low.startswith(k) and len(low) <= len(k) + 10:
  377. # 后面只能带一点点后缀(版本号、角色名之类);
  378. # "冒险岛测谎界面提醒工具 — 聊天窗口" 这种就不算了
  379. score = max(score, 2)
  380. elif k in low:
  381. score = max(score, 1)
  382. if not score:
  383. continue
  384. try:
  385. if user32.IsIconic(hwnd):
  386. continue
  387. except Exception:
  388. pass
  389. x, y, w, h = client_rect(hwnd)
  390. if w < 320 or h < 240:
  391. continue
  392. area = w * h
  393. rank = (score, -len(title.strip()), area)
  394. if best is None or rank > best[0]:
  395. best = (rank, hwnd, (x, y, w, h))
  396. if best is None or best[0][0] < 2:
  397. return 0, None
  398. return best[1], best[2]
  399. def game_window_minimized(titles: List[str]) -> bool:
  400. """游戏窗口在、但是被最小化了(最小化时截不到画面,只能待机)。"""
  401. keys = [k.strip().lower() for k in titles if k and k.strip()]
  402. for hwnd, title in iter_windows():
  403. if not title:
  404. continue
  405. low = title.strip().lower()
  406. if not any(low == k or (low.startswith(k) and len(low) <= len(k) + 10)
  407. or k in low for k in keys):
  408. continue
  409. try:
  410. if user32.IsIconic(hwnd):
  411. return True
  412. except Exception:
  413. pass
  414. return False
  415. def force_foreground(hwnd: int) -> bool:
  416. """把窗口拉到最前。Windows 会拦后台程序抢焦点,按一下 Alt 解锁再抢。"""
  417. if not hwnd:
  418. return False
  419. try:
  420. if user32.IsIconic(hwnd):
  421. user32.ShowWindow(hwnd, 9) # SW_RESTORE
  422. user32.keybd_event(0x12, 0, 0, 0) # Alt down
  423. user32.keybd_event(0x12, 0, 2, 0) # Alt up
  424. user32.SetForegroundWindow(hwnd)
  425. user32.BringWindowToTop(hwnd)
  426. return True
  427. except Exception:
  428. return False
  429. def flash_window(hwnd: int) -> None:
  430. """任务栏图标闪。"""
  431. class FLASHWINFO(ctypes.Structure):
  432. _fields_ = [("cbSize", wintypes.UINT), ("hwnd", wintypes.HWND),
  433. ("dwFlags", wintypes.DWORD), ("uCount", wintypes.UINT),
  434. ("dwTimeout", wintypes.DWORD)]
  435. try:
  436. info = FLASHWINFO(ctypes.sizeof(FLASHWINFO), hwnd, 0x00000003, 8, 0)
  437. user32.FlashWindowEx(ctypes.byref(info))
  438. except Exception:
  439. pass
  440. # ---------------------------------------------------------------- 模板与匹配
  441. class Template:
  442. __slots__ = ("name", "gray", "_cache")
  443. def __init__(self, name: str, gray: np.ndarray):
  444. self.name = name
  445. self.gray = gray
  446. self._cache: Dict[float, np.ndarray] = {}
  447. def scaled(self, scale: float) -> np.ndarray:
  448. key = round(scale, 3)
  449. hit = self._cache.get(key)
  450. if hit is not None:
  451. return hit
  452. h, w = self.gray.shape[:2]
  453. nh = max(4, int(round(h * scale)))
  454. nw = max(4, int(round(w * scale)))
  455. interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_LINEAR
  456. img = cv2.resize(self.gray, (nw, nh), interpolation=interp)
  457. self._cache[key] = img
  458. return img
  459. class TemplateStore:
  460. """templates/ 目录里的所有 png。支持运行中新增(learn 模式)自动生效。"""
  461. def __init__(self, directory: Path):
  462. self.dir = directory
  463. self.items: List[Template] = []
  464. self._sig = None
  465. self.reload()
  466. def _signature(self):
  467. try:
  468. return tuple(sorted((p.name, p.stat().st_mtime_ns)
  469. for p in self.dir.glob("*.png")))
  470. except Exception:
  471. return ()
  472. def reload(self) -> List[Template]:
  473. items: List[Template] = []
  474. try:
  475. for path in sorted(self.dir.glob("*.png")):
  476. img = imread_gray(path)
  477. if img is None or min(img.shape[:2]) < 10:
  478. continue
  479. items.append(Template(path.stem, img))
  480. except Exception:
  481. pass
  482. items.sort(key=lambda t: t.gray.size) # 小的先试,便宜
  483. self.items = items
  484. self._sig = self._signature()
  485. return items
  486. def maybe_reload(self) -> bool:
  487. if self._signature() != self._sig:
  488. self.reload()
  489. return True
  490. return False
  491. class MatchHit:
  492. __slots__ = ("score", "coarse", "name", "scale", "rect", "verified")
  493. def __init__(self, score: float = 0.0, coarse: float = 0.0, name: str = "",
  494. scale: float = 1.0, rect: Tuple[int, int, int, int] = (0, 0, 0, 0),
  495. verified: bool = False):
  496. self.score = score # 最终分数(复核过就是全分辨率分数)
  497. self.coarse = coarse # 粗查分数
  498. self.name = name
  499. self.scale = scale
  500. self.rect = rect
  501. self.verified = verified
  502. def __repr__(self) -> str:
  503. return "MatchHit(%.3f, %s, x%.2f, %s)" % (self.score, self.name,
  504. self.scale, self.rect)
  505. class Matcher:
  506. """多尺度模板匹配。
  507. 全分辨率跑一遍要命(1000x750 一张 55ms,20 个组合就是 1 秒多),
  508. 所以:先把画面缩小 scale_down 倍做粗查,粗查可疑时再用全分辨率复核。
  509. 粗查负责"快",复核负责"准"。
  510. """
  511. def __init__(self, templates: List[Template], scales: List[float],
  512. threshold: float, scale_down: float = 2.0):
  513. # 大模板信息量大,先试它,一次命中就能早退
  514. self.templates = sorted(templates, key=lambda t: -int(t.gray.size))
  515. self.scales = list(scales)
  516. self.threshold = float(threshold)
  517. self.scale_down = max(1.0, float(scale_down))
  518. # 粗查多少分以上才值得花大价钱做全分辨率复核。
  519. # 实测:纯背景 0.57,但游戏画面里到处是小字,半分辨率下噪声能到 0.67;
  520. # 真对话框粗查是 0.85+,所以门槛放在 0.70 既不会白忙也不漏
  521. self.coarse_threshold = max(0.70, self.threshold)
  522. def _template(self, name: str) -> Optional[Template]:
  523. for tpl in self.templates:
  524. if tpl.name == name:
  525. return tpl
  526. return None
  527. def _scan(self, gray: np.ndarray, eff_scales: List[float], ds: float,
  528. early_exit: bool, stop_at: float):
  529. H, W = gray.shape[:2]
  530. best = MatchHit()
  531. per: Dict[str, dict] = {}
  532. for tpl in self.templates:
  533. s_best, s_scale, s_loc, s_size = -1.0, 1.0, None, (0, 0)
  534. for eff in eff_scales:
  535. tm = tpl.scaled(eff)
  536. th, tw = tm.shape[:2]
  537. if tw > W or th > H or tw < 10 or th < 6:
  538. continue
  539. try:
  540. res = cv2.matchTemplate(gray, tm, cv2.TM_CCOEFF_NORMED)
  541. except cv2.error:
  542. continue
  543. res = np.nan_to_num(res, nan=0.0, posinf=0.0, neginf=0.0)
  544. _, mx, _, loc = cv2.minMaxLoc(res)
  545. if mx > s_best:
  546. s_best, s_scale, s_loc, s_size = float(mx), eff, loc, (tw, th)
  547. if early_exit and s_best >= stop_at:
  548. break
  549. if s_loc is None:
  550. continue
  551. rect = (int(s_loc[0] * ds), int(s_loc[1] * ds),
  552. int(s_size[0] * ds), int(s_size[1] * ds))
  553. per[tpl.name] = {"score": s_best, "scale": s_scale * ds, "rect": rect}
  554. if s_best > best.coarse:
  555. best = MatchHit(score=s_best, coarse=s_best, name=tpl.name,
  556. scale=s_scale * ds, rect=rect)
  557. return best, per
  558. def match(self, gray: np.ndarray, early_exit: bool = True, full: bool = False):
  559. """返回 (最佳 MatchHit, {模板名: {score, scale, rect}})。
  560. per 里带位置,方便把"到底匹配到哪块"画出来查误报。
  561. full=True 时全分辨率、全档位、不早退 —— 给 check/once 调参用,慢但最准。
  562. """
  563. ds = 1.0
  564. work = gray
  565. if not full and self.scale_down > 1.01:
  566. ds = self.scale_down
  567. # 大画面再多缩一点,不然全屏 1920x1080 会把一个核吃满
  568. px = gray.shape[0] * gray.shape[1]
  569. if px > 1.4e6:
  570. ds = max(ds, 3.0)
  571. nw = max(32, int(round(gray.shape[1] / ds)))
  572. nh = max(32, int(round(gray.shape[0] / ds)))
  573. work = cv2.resize(gray, (nw, nh), interpolation=cv2.INTER_AREA)
  574. eff = [s / ds for s in self.scales] if ds > 1.0 else list(self.scales)
  575. stop_at = self.threshold if full else max(0.85, self.threshold)
  576. hit, per = self._scan(work, eff, ds, early_exit and not full, stop_at)
  577. if full or hit.coarse < self.coarse_threshold:
  578. return hit, per
  579. # 粗查可疑 → 全分辨率复核,确认了才算数(宁可漏一顿,不要误报)
  580. tpl = self._template(hit.name)
  581. if tpl is None:
  582. return hit, per
  583. best_score = hit.coarse
  584. best_scale = hit.scale
  585. best_rect = hit.rect
  586. # 先按粗查给出的那个档位复核;过了就收工,没过再试相邻的 ±2.5%
  587. for sv in (hit.scale, hit.scale * 0.975, hit.scale * 1.025):
  588. tm = tpl.scaled(sv)
  589. if tm.shape[0] > gray.shape[0] or tm.shape[1] > gray.shape[1]:
  590. continue
  591. try:
  592. res = cv2.matchTemplate(gray, tm, cv2.TM_CCOEFF_NORMED)
  593. except cv2.error:
  594. continue
  595. res = np.nan_to_num(res, nan=0.0, posinf=0.0, neginf=0.0)
  596. _, mx, _, loc = cv2.minMaxLoc(res)
  597. if mx > best_score:
  598. best_score = float(mx)
  599. best_scale = sv
  600. best_rect = (int(loc[0]), int(loc[1]),
  601. int(tm.shape[1]), int(tm.shape[0]))
  602. if best_score >= self.threshold:
  603. break
  604. per[hit.name] = {"score": best_score, "scale": best_scale,
  605. "rect": best_rect}
  606. return MatchHit(best_score, hit.coarse, hit.name, best_scale, best_rect,
  607. verified=True), per
  608. def count_hits(per: Dict[str, dict], threshold: float) -> int:
  609. """这一帧里有多少个模板过了阈值。"""
  610. return sum(1 for v in per.values() if float(v.get("score", 0.0)) >= threshold)
  611. def _hit_items(per: Dict[str, dict], threshold: float):
  612. """过阈值的 (名字, info),按分数从高到低。"""
  613. items = [(n, v) for n, v in per.items()
  614. if float(v.get("score", 0.0)) >= threshold]
  615. items.sort(key=lambda kv: -float(kv[1].get("score", 0.0)))
  616. return items
  617. def cluster_hits(per: Dict[str, dict], threshold: float,
  618. soft: float = 0.0) -> List[Tuple[str, dict]]:
  619. """把过线(或接近过线)的模板收成「同一块对话框」里的一组。
  620. 真测谎窗:标题/倒计时/说明/规则挤在约 370×220(×缩放)的白窗里,缩放一致。
  621. 误报常见:聊天区两处各撞上一个模板,中心相距很远或缩放对不上。
  622. """
  623. hard = _hit_items(per, threshold)
  624. soft_thr = max(0.45, float(soft) if soft > 0 else threshold - 0.12)
  625. pool = _hit_items(per, soft_thr)
  626. if not pool:
  627. return []
  628. def _center(info: dict):
  629. x, y, w, h = info.get("rect", (0, 0, 0, 0))
  630. return (x + w * 0.5, y + h * 0.5)
  631. def _scale(info: dict) -> float:
  632. return max(0.2, float(info.get("scale", 1.0)))
  633. # 以最高分为锚点,吸入缩放接近、距离在对话框范围内的其它块
  634. anchor_name, anchor = pool[0]
  635. as_ = _scale(anchor)
  636. ax, ay = _center(anchor)
  637. max_dx = 420.0 * as_
  638. max_dy = 280.0 * as_
  639. clustered = [(anchor_name, anchor)]
  640. for name, info in pool[1:]:
  641. if abs(_scale(info) / as_ - 1.0) > 0.10:
  642. continue
  643. cx, cy = _center(info)
  644. if abs(cx - ax) <= max_dx and abs(cy - ay) <= max_dy:
  645. clustered.append((name, info))
  646. # 整簇外接矩形也不能大得离谱(挡住「锚点附近刚好各有一块」但其实横跨半屏)
  647. if len(clustered) >= 2:
  648. left = min(v["rect"][0] for _, v in clustered)
  649. right = max(v["rect"][0] + v["rect"][2] for _, v in clustered)
  650. top = min(v["rect"][1] for _, v in clustered)
  651. bot = max(v["rect"][1] + v["rect"][3] for _, v in clustered)
  652. if (right - left) > 560.0 * as_ or (bot - top) > 380.0 * as_:
  653. # 退回:只留硬过线且彼此仍近的
  654. clustered = [(n, v) for n, v in clustered
  655. if float(v.get("score", 0.0)) >= threshold]
  656. if len(clustered) >= 2:
  657. left = min(v["rect"][0] for _, v in clustered)
  658. right = max(v["rect"][0] + v["rect"][2] for _, v in clustered)
  659. top = min(v["rect"][1] for _, v in clustered)
  660. bot = max(v["rect"][1] + v["rect"][3] for _, v in clustered)
  661. if (right - left) > 560.0 * as_ or (bot - top) > 380.0 * as_:
  662. return hard[:1]
  663. # 有标题时,标题应在其它块上方(测谎窗标题贴顶)
  664. by_name = {n: v for n, v in clustered}
  665. title = None
  666. for key in by_name:
  667. if key == "01_title" or key.endswith("_title") or "title" in key.lower():
  668. title = by_name[key]
  669. break
  670. if title is not None and len(clustered) >= 2:
  671. ty = title["rect"][1] + title["rect"][3] * 0.5
  672. others_y = [v["rect"][1] + v["rect"][3] * 0.5
  673. for n, v in clustered if v is not title]
  674. if others_y and ty > min(others_y) + 30 * as_:
  675. return [(n, v) for n, v in clustered if v is not title][:1] or hard[:1]
  676. return clustered
  677. def is_confirmed(hit, per: Dict[str, dict], threshold: float, min_hits: int,
  678. strong: float, require_layout: bool = True,
  679. pair_avg: float = 0.82) -> bool:
  680. """要不要认定「测谎仪出现了」。
  681. 比「过线个数」多两道闸:
  682. 1) 命中块必须挤在对话框大小的区域里(require_layout)
  683. 2) 只有 2 个模板过线时,平均分还要够高(挡聊天区擦边球)
  684. 超高分单模板仍可认,但附近还得有第二块「像」的,避免标题撞字。
  685. """
  686. if hit is None or hit.score < min(threshold, strong):
  687. # 连 soft 都不够,直接否
  688. if hit is None or hit.score < threshold * 0.85:
  689. return False
  690. clustered = cluster_hits(per, threshold) if require_layout else _hit_items(per, threshold)
  691. hard = [(n, v) for n, v in clustered
  692. if float(v.get("score", 0.0)) >= threshold]
  693. hits = len(hard)
  694. best = float(hard[0][1]["score"]) if hard else float(hit.score)
  695. if hits >= max(3, min_hits + 1):
  696. return best >= threshold
  697. if hits >= min_hits:
  698. avg = sum(float(v["score"]) for _, v in hard) / float(hits)
  699. # 两个擦边(0.70/0.72)平均只有 0.71,过不了 pair_avg;真窗通常 0.9+
  700. if hits == 2 and avg < float(pair_avg):
  701. return False
  702. return best >= threshold
  703. # 强命中兜底:主分很高,且同簇里还有第二块接近阈值的
  704. if best >= strong or hit.score >= strong:
  705. soft = cluster_hits(per, threshold, soft=threshold - 0.10) if require_layout \
  706. else _hit_items(per, threshold - 0.10)
  707. near = len(soft)
  708. if near >= 2 and (best >= strong or hit.score >= strong):
  709. return True
  710. # 极高分且已全分辨率复核过,才允许单模板(几乎不可能是巧合)
  711. if hit.verified and hit.score >= max(strong, 0.96):
  712. return True
  713. return False
  714. def estimate_ui_scale(gray: np.ndarray, hud_labels: Dict[str, np.ndarray],
  715. candidates: Optional[List[float]] = None) -> Optional[float]:
  716. """用底部 HP/MP/EXP 标签推算当前 UI 相对模板的缩放。
  717. 标签几乎每帧都在,比盲扫测谎模板更稳;分辨率/DPI 变了这里最先反映出来。
  718. """
  719. if gray is None or gray.shape[0] < 80 or not hud_labels:
  720. return None
  721. scales = candidates or [
  722. 1.0, 0.95, 1.05, 0.9, 1.1, 0.85, 1.15, 0.8, 1.2,
  723. 0.75, 1.25, 0.7, 1.35, 0.65, 1.5,
  724. ]
  725. y0 = max(0, gray.shape[0] - max(80, int(gray.shape[0] * 0.12)))
  726. strip = gray[y0:]
  727. best_s, best_sc = 1.0, -1.0
  728. # 优先用 HP,没有就试 MP/EXP
  729. order = [k for k in ("hp", "mp", "exp") if k in hud_labels]
  730. if not order:
  731. return None
  732. for key in order:
  733. tpl = hud_labels[key]
  734. th0, tw0 = tpl.shape[:2]
  735. for s in scales:
  736. nh = max(4, int(round(th0 * s)))
  737. nw = max(4, int(round(tw0 * s)))
  738. if nh >= strip.shape[0] or nw >= strip.shape[1]:
  739. continue
  740. interp = cv2.INTER_AREA if s < 1.0 else cv2.INTER_LINEAR
  741. tm = cv2.resize(tpl, (nw, nh), interpolation=interp)
  742. try:
  743. res = cv2.matchTemplate(strip, tm, cv2.TM_CCOEFF_NORMED)
  744. except cv2.error:
  745. continue
  746. res = np.nan_to_num(res, nan=0.0, posinf=0.0, neginf=0.0)
  747. sc = float(cv2.minMaxLoc(res)[1])
  748. if sc > best_sc:
  749. best_sc, best_s = sc, float(s)
  750. if best_sc >= 0.70:
  751. return round(best_s, 3)
  752. return round(best_s, 3) if best_sc >= 0.55 else None
  753. def annotate(gray: np.ndarray, per: Dict[str, dict], threshold: float,
  754. winner: str = ""):
  755. """把每个模板匹配到的位置画到图上:绿框=过了阈值,橙框=有几分像但没过。
  756. 存现场截图时用,误报了能一眼看出它是拿哪块画面当的测谎仪。
  757. """
  758. img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
  759. h, w = img.shape[:2]
  760. for name, info in sorted(per.items(), key=lambda kv: -float(kv[1].get("score", 0.0))):
  761. sc = float(info.get("score", 0.0))
  762. if sc < max(0.50, threshold - 0.25):
  763. continue
  764. bx, by, bw, bh = [int(v) for v in info.get("rect", (0, 0, 0, 0))]
  765. if bw <= 0 or bh <= 0:
  766. continue
  767. x0, y0 = max(0, bx), max(0, by)
  768. x1, y1 = min(w - 1, bx + bw), min(h - 1, by + bh)
  769. ok = sc >= threshold
  770. if ok and name == winner:
  771. color = (60, 255, 60)
  772. elif ok:
  773. color = (60, 200, 60)
  774. else:
  775. color = (60, 170, 255)
  776. cv2.rectangle(img, (x0, y0), (x1, y1), color, 2 if ok else 1)
  777. label = "%s %.2f" % (name, sc)
  778. ty = y0 - 6 if y0 > 18 else y1 + 16
  779. cv2.putText(img, label, (x0 + 2, ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
  780. (0, 0, 0), 3, cv2.LINE_AA)
  781. cv2.putText(img, label, (x0 + 2, ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
  782. color, 1, cv2.LINE_AA)
  783. head = "threshold %.2f matches %d/%d" % (
  784. threshold, count_hits(per, threshold), len(per))
  785. cv2.putText(img, head, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
  786. (0, 0, 0), 4, cv2.LINE_AA)
  787. cv2.putText(img, head, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
  788. (255, 255, 255), 1, cv2.LINE_AA)
  789. return img
  790. # ---------------------------------------------------------------- 警报音
  791. def ensure_alarm_wav(path: Path, volume: float) -> Optional[Path]:
  792. """没有就现场合成一段双音警笛 wav(不用去网上找铃声)。"""
  793. try:
  794. if path.exists() and path.stat().st_size > 2000:
  795. return path
  796. path.parent.mkdir(parents=True, exist_ok=True)
  797. sr = 44100
  798. seg = []
  799. for _ in range(2):
  800. for freq in (880.0, 660.0):
  801. t = np.arange(int(sr * 0.22)) / sr
  802. tone = (0.60 * np.sin(2 * np.pi * freq * t)
  803. + 0.25 * np.sin(2 * np.pi * 2 * freq * t)
  804. + 0.12 * np.sin(2 * np.pi * 3 * freq * t))
  805. env = np.ones_like(t)
  806. n = max(1, int(sr * 0.012))
  807. env[:n] = np.linspace(0.0, 1.0, n)
  808. env[-n:] = np.linspace(1.0, 0.0, n)
  809. seg.append(tone * env)
  810. data = np.concatenate(seg)
  811. peak = float(np.max(np.abs(data))) or 1.0
  812. data = np.clip(data / peak * max(0.05, min(1.0, volume)), -1.0, 1.0)
  813. pcm = (data * 32767.0).astype("<i2")
  814. with wave.open(str(path), "wb") as fh:
  815. fh.setnchannels(1)
  816. fh.setsampwidth(2)
  817. fh.setframerate(sr)
  818. fh.writeframes(pcm.tobytes())
  819. return path
  820. except Exception:
  821. return None
  822. def speak_async(text: str) -> None:
  823. """用系统自带的语音合成念一句,失败就算了。"""
  824. def _run():
  825. try:
  826. import base64
  827. import subprocess
  828. script = (
  829. "Add-Type -AssemblyName System.Speech;"
  830. "$s=New-Object System.Speech.Synthesis.SpeechSynthesizer;"
  831. "$s.Rate=1;$s.Speak('%s')" % text.replace("'", "''")
  832. )
  833. enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
  834. subprocess.run(
  835. ["powershell", "-NoProfile", "-NonInteractive", "-EncodedCommand", enc],
  836. creationflags=0x08000000, # CREATE_NO_WINDOW
  837. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  838. timeout=20,
  839. )
  840. except Exception:
  841. pass
  842. threading.Thread(target=_run, daemon=True).start()
  843. # ---------------------------------------------------------------- 血蓝 / 经验
  844. def ensure_hp_wav(path: Path, volume: float) -> Optional[Path]:
  845. """低血提示音:轻轻两声「叮咚」,跟测谎那种连响警笛明显不一样。"""
  846. try:
  847. if path.exists() and path.stat().st_size > 1000:
  848. return path
  849. path.parent.mkdir(parents=True, exist_ok=True)
  850. sr = 44100
  851. seg = []
  852. for freq, dur in ((988.0, 0.12), (0.0, 0.05), (740.0, 0.16)):
  853. if freq <= 0:
  854. seg.append(np.zeros(int(sr * dur)))
  855. continue
  856. t = np.arange(int(sr * dur)) / sr
  857. tone = np.sin(2 * np.pi * freq * t) + 0.2 * np.sin(2 * np.pi * 2 * freq * t)
  858. env = np.ones_like(t)
  859. n = max(1, int(sr * 0.008))
  860. env[:n] = np.linspace(0.0, 1.0, n)
  861. tail = max(1, int(sr * 0.05))
  862. env[-tail:] = np.linspace(1.0, 0.0, tail)
  863. seg.append(tone * env)
  864. data = np.concatenate(seg)
  865. peak = float(np.max(np.abs(data))) or 1.0
  866. data = np.clip(data / peak * max(0.05, min(1.0, volume)), -1.0, 1.0)
  867. pcm = (data * 32767.0).astype("<i2")
  868. with wave.open(str(path), "wb") as fh:
  869. fh.setnchannels(1)
  870. fh.setsampwidth(2)
  871. fh.setframerate(sr)
  872. fh.writeframes(pcm.tobytes())
  873. return path
  874. except Exception:
  875. return None
  876. class HudReader:
  877. """读游戏画面底部那条「HP / MP / EXP」栏。
  878. 这游戏用的是无抗锯齿点阵字体:同一个字每次画出来的像素完全一样
  879. (实测两张不同时刻的截图,同一段数字逐像素完全相等)。
  880. 所以这里不用 OCR,而是把每个字切成小块、跟模板逐像素比对:
  881. 数字是 100% 准的,也不会出现「/ 被认成 .」这种错。
  882. """
  883. GLYPHS = {"0": "0", "1": "1", "2": "2", "3": "3", "4": "4",
  884. "5": "5", "6": "6", "7": "7", "8": "8", "9": "9",
  885. "lparen": "(", "rparen": ")", "slash": "/", "dot": ".",
  886. "pct": "%"}
  887. def __init__(self, directory: Path = HUD_DIR):
  888. self.dir = directory
  889. self.by_shape: Dict[tuple, List[Tuple[str, np.ndarray]]] = {}
  890. self.labels: Dict[str, np.ndarray] = {}
  891. self.fails = 0
  892. self._load()
  893. def _load(self) -> None:
  894. for name, ch in self.GLYPHS.items():
  895. img = imread_gray(self.dir / (name + ".png"))
  896. if img is None:
  897. continue
  898. bits = img > 150
  899. self.by_shape.setdefault(bits.shape, []).append((ch, bits))
  900. for key in ("hp", "mp", "exp"):
  901. img = imread_gray(self.dir / (key + ".png"))
  902. if img is not None:
  903. self.labels[key] = img
  904. @property
  905. def ready(self) -> bool:
  906. return bool(self.by_shape) and len(self.labels) == 3
  907. # ---- 按空白列把一段文字切成一个个字
  908. @staticmethod
  909. def _segments(bits: np.ndarray, y: int, h: int, x0: int, x1: int):
  910. cols = bits[y:y + h, x0:x1].any(axis=0)
  911. out, start = [], None
  912. for i, on in enumerate(cols):
  913. if on and start is None:
  914. start = i
  915. elif not on and start is not None:
  916. out.append((x0 + start, x0 + i))
  917. start = None
  918. if start is not None:
  919. out.append((x0 + start, x1))
  920. return out
  921. def _char(self, bits, y: int, h: int, x0: int, x1: int) -> str:
  922. piece = bits[y:y + h, x0:x1]
  923. for ch, tpl in self.by_shape.get(piece.shape, ()):
  924. if np.array_equal(piece, tpl):
  925. return ch
  926. return "?"
  927. def _text(self, bits, y: int, h: int, x0: int, x1: int) -> str:
  928. return "".join(self._char(bits, y, h, a, b)
  929. for a, b in self._segments(bits, y, h, x0, x1))
  930. def _scaled_bits(self, scale: float) -> Dict[tuple, List[Tuple[str, np.ndarray]]]:
  931. """按 UI 缩放生成一份字形模板;1.0 直接复用启动时那份。"""
  932. if abs(scale - 1.0) < 0.03:
  933. return self.by_shape
  934. out: Dict[tuple, List[Tuple[str, np.ndarray]]] = {}
  935. for _shape, items in self.by_shape.items():
  936. for ch, bits in items:
  937. h, w = bits.shape
  938. nh = max(1, int(round(h * scale)))
  939. nw = max(1, int(round(w * scale)))
  940. img = (bits.astype(np.uint8) * 255)
  941. interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_NEAREST
  942. resized = cv2.resize(img, (nw, nh), interpolation=interp)
  943. rb = resized > 127
  944. out.setdefault(rb.shape, []).append((ch, rb))
  945. return out
  946. def _char_scaled(self, bits, y, h, x0, x1, by_shape) -> str:
  947. piece = bits[y:y + h, x0:x1]
  948. for ch, tpl in by_shape.get(piece.shape, ()):
  949. if np.array_equal(piece, tpl):
  950. return ch
  951. # 缩放后逐像素可能差 1px,退一步用重合率
  952. best_ch, best = "?", 0.0
  953. ph, pw = piece.shape
  954. for shape, items in by_shape.items():
  955. if abs(shape[0] - ph) > 1 or abs(shape[1] - pw) > 2:
  956. continue
  957. for ch, tpl in items:
  958. th, tw = tpl.shape
  959. hh, ww = min(ph, th), min(pw, tw)
  960. if hh < 1 or ww < 1:
  961. continue
  962. a = piece[:hh, :ww]
  963. b = tpl[:hh, :ww]
  964. denom = float(hh * ww)
  965. score = float(np.count_nonzero(a == b)) / denom
  966. if score > best:
  967. best, best_ch = score, ch
  968. return best_ch if best >= 0.82 else "?"
  969. def _text_scaled(self, bits, y, h, x0, x1, by_shape) -> str:
  970. return "".join(self._char_scaled(bits, y, h, a, b, by_shape)
  971. for a, b in self._segments(bits, y, h, x0, x1))
  972. # ---- 主入口:传进一帧普通灰度图(游戏客户区),返回三项,读不到就是 None
  973. def read(self, gray: np.ndarray,
  974. ui_scale: float = 1.0) -> Dict[str, Optional[tuple]]:
  975. out: Dict[str, Optional[tuple]] = {"hp": None, "mp": None, "exp": None}
  976. if not self.ready or gray is None or gray.shape[0] < 120:
  977. return out
  978. scale = float(ui_scale) if ui_scale and ui_scale > 0 else 1.0
  979. band = max(48, int(round(60 * max(0.7, min(1.8, scale)))))
  980. y0 = max(0, gray.shape[0] - band) # HUD 就贴在画面最底下
  981. strip = gray[y0:]
  982. bits = strip > 150
  983. by_shape = self._scaled_bits(scale)
  984. for key in ("hp", "mp", "exp"):
  985. tpl = self.labels.get(key)
  986. if tpl is None:
  987. continue
  988. th0, tw0 = tpl.shape[:2]
  989. nh = max(4, int(round(th0 * scale)))
  990. nw = max(4, int(round(tw0 * scale)))
  991. if nh >= strip.shape[0] or nw >= strip.shape[1]:
  992. continue
  993. interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_LINEAR
  994. tm = tpl if abs(scale - 1.0) < 0.03 else cv2.resize(
  995. tpl, (nw, nh), interpolation=interp)
  996. try:
  997. res = cv2.matchTemplate(strip, tm, cv2.TM_CCOEFF_NORMED)
  998. except cv2.error:
  999. continue
  1000. _mn, score, _ml, loc = cv2.minMaxLoc(res)
  1001. if score < 0.55:
  1002. continue
  1003. th, tw = tm.shape[:2]
  1004. y, x = loc[1], loc[0] + tw
  1005. span = min(x + max(120, int(150 * scale)), strip.shape[1])
  1006. text = self._text_scaled(bits, y, th, x, span, by_shape)
  1007. if key == "exp":
  1008. m = re.match(r"(\d+)\((\d+)\.(\d+)%\)", text)
  1009. if m:
  1010. out["exp"] = (int(m.group(1)),
  1011. float(m.group(2) + "." + m.group(3)))
  1012. else:
  1013. m = re.match(r"\((\d+)/(\d+)\)", text)
  1014. if m and int(m.group(2)) > 0:
  1015. out[key] = (int(m.group(1)), int(m.group(2)))
  1016. if all(v is None for v in out.values()):
  1017. self.fails += 1
  1018. return out
  1019. class HudAlert:
  1020. """血量/蓝量过低提醒。
  1021. 做得比测谎「轻」:短促两声 + 右上角一条小提示,不抢焦点、不切窗口,
  1022. 也不会把测谎那套连响警笛打开——两者互不影响。
  1023. """
  1024. def __init__(self, cfg: dict, popup_sink=None, quiet: bool = False):
  1025. self.cfg = cfg.get("hp_alert", {})
  1026. self.sink = popup_sink
  1027. self.quiet = quiet
  1028. self.count = 0
  1029. self._last = {"hp": 0.0, "mp": 0.0}
  1030. self._wav = None
  1031. if self.cfg.get("sound", True) and not quiet:
  1032. self._wav = ensure_hp_wav(ASSET_DIR / "hp_low.wav",
  1033. float(self.cfg.get("volume", 0.45)))
  1034. def reset(self) -> None:
  1035. self._last = {"hp": 0.0, "mp": 0.0}
  1036. def check(self, now: float, hp_pct, mp_pct) -> None:
  1037. if not self.cfg.get("enabled", True):
  1038. return
  1039. repeat = max(5.0, float(self.cfg.get("repeat_seconds", 30)))
  1040. jobs = []
  1041. if hp_pct is not None:
  1042. low = float(self.cfg.get("low_pct", 30))
  1043. rec = float(self.cfg.get("recover_pct", low + 5))
  1044. if hp_pct >= rec:
  1045. self._last["hp"] = 0.0
  1046. elif hp_pct < low:
  1047. if self._last["hp"] == 0.0 or now - self._last["hp"] >= repeat:
  1048. self._last["hp"] = now
  1049. jobs.append(("hp", hp_pct))
  1050. if self.cfg.get("mp_enabled", True) and mp_pct is not None:
  1051. low = float(self.cfg.get("mp_low_pct", 10))
  1052. rec = float(self.cfg.get("mp_recover_pct", low + 5))
  1053. if mp_pct >= rec:
  1054. self._last["mp"] = 0.0
  1055. elif mp_pct < low:
  1056. if self._last["mp"] == 0.0 or now - self._last["mp"] >= repeat:
  1057. self._last["mp"] = now
  1058. jobs.append(("mp", mp_pct))
  1059. for kind, pct in jobs:
  1060. self.fire(kind, pct)
  1061. def fire(self, kind: str, pct: float) -> None:
  1062. self.count += 1
  1063. label = "血量" if kind == "hp" else "蓝量"
  1064. log("· %s只剩 %.0f%%" % (label, pct))
  1065. if self.cfg.get("sound", True) and not self.quiet and self._wav is not None:
  1066. try:
  1067. import winsound
  1068. winsound.PlaySound(str(self._wav),
  1069. winsound.SND_FILENAME | winsound.SND_ASYNC)
  1070. except Exception:
  1071. pass
  1072. if self.cfg.get("popup", True) and self.sink is not None:
  1073. self.sink({
  1074. "kind": kind,
  1075. "title": "%s只剩 %.0f%%" % (label, pct),
  1076. "text": "记得喝药 / 回城补血" if kind == "hp" else "记得补蓝",
  1077. "seconds": float(self.cfg.get("popup_seconds", 6)),
  1078. })
  1079. def fmt_exp(value: Optional[float]) -> str:
  1080. """把经验数字变成 1.23亿 / 4567万 这种好认的形式。"""
  1081. if value is None:
  1082. return "--"
  1083. try:
  1084. value = float(value)
  1085. except Exception:
  1086. return "--"
  1087. if value >= 1e8:
  1088. return "%.2f亿" % (value / 1e8)
  1089. if value >= 1e4:
  1090. return "%.1f万" % (value / 1e4)
  1091. return "%d" % int(value)
  1092. def fmt_duration(seconds: Optional[float]) -> str:
  1093. if seconds is None or seconds <= 0 or seconds > 86400 * 30:
  1094. return "--"
  1095. seconds = int(seconds)
  1096. h, m = seconds // 3600, (seconds % 3600) // 60
  1097. if h:
  1098. return "%d小时%d分" % (h, m)
  1099. if m:
  1100. return "%d分" % m
  1101. return "%d秒" % seconds
  1102. class ExpTrack:
  1103. """经验采样 + 统计。
  1104. 数据来源就是 HUD 上那个「EXP 1007297(43.89%)」:
  1105. 当前经验 + 当前等级百分比 → 反推出这一级总共需要多少经验,
  1106. 于是能算「还差多少」「按现在的速度还要多久升级」。
  1107. """
  1108. def __init__(self, cfg: dict):
  1109. c = cfg.get("exp", {})
  1110. self.cfg = c
  1111. self.interval = max(2.0, float(c.get("sample_seconds", 10)))
  1112. self.window = max(1.0, float(c.get("window_minutes", 5)))
  1113. self.save_csv = bool(c.get("save_csv", True))
  1114. self.samples: List[Tuple[float, int, float]] = []
  1115. self.rate_hist: List[Tuple[float, float]] = [] # (时间, 当时算出的实时1H)
  1116. self._last_t = 0.0
  1117. self._seg_start = 0.0 # 当前这一级从哪个样本开始
  1118. self._csv = None
  1119. self._csv_day = ""
  1120. # ---- 采样
  1121. def feed(self, now: float, exp_val: int, exp_pct: float,
  1122. hp=None, mp=None) -> None:
  1123. if exp_val <= 0 or exp_pct <= 0:
  1124. return
  1125. if self.samples and now - self._last_t < self.interval:
  1126. return
  1127. prev = self.samples[-1] if self.samples else None
  1128. if prev is not None and exp_val < prev[1]:
  1129. # 经验变少 = 升级了(或换了角色),这一段的统计重新开始
  1130. self._seg_start = now
  1131. self.samples.append((now, exp_val, exp_pct))
  1132. self._last_t = now
  1133. self._write_csv(now, exp_val, exp_pct, hp, mp)
  1134. return
  1135. self.samples.append((now, exp_val, exp_pct))
  1136. self._last_t = now
  1137. self._trim(now)
  1138. rate = self.rate_1h(now)
  1139. if rate is not None:
  1140. self.rate_hist.append((now, rate))
  1141. cut = now - 3600
  1142. while self.rate_hist and self.rate_hist[0][0] < cut:
  1143. self.rate_hist.pop(0)
  1144. self._write_csv(now, exp_val, exp_pct, hp, mp)
  1145. def _trim(self, now: float) -> None:
  1146. cut = now - 4 * 3600
  1147. while self.samples and self.samples[0][0] < cut:
  1148. self.samples.pop(0)
  1149. def _write_csv(self, now, exp_val, exp_pct, hp, mp) -> None:
  1150. if not self.save_csv:
  1151. return
  1152. try:
  1153. day = time.strftime("%Y%m%d", time.localtime(now))
  1154. if self._csv is None or day != self._csv_day or self._csv.closed:
  1155. if self._csv is not None and not self._csv.closed:
  1156. self._csv.close()
  1157. LOG_DIR.mkdir(parents=True, exist_ok=True)
  1158. path = LOG_DIR / ("exp_%s.csv" % day)
  1159. new = not path.exists()
  1160. self._csv = open(path, "a", encoding="utf-8-sig", newline="")
  1161. self._csv_day = day
  1162. if new:
  1163. self._csv.write("时间,经验,百分比,实时1H,HP,MP\n")
  1164. rate = self.rate_1h(now) or 0.0
  1165. self._csv.write("%s,%d,%.2f,%d,%s,%s\n" % (
  1166. time.strftime("%H:%M:%S", time.localtime(now)), exp_val,
  1167. exp_pct, int(rate), hp if hp is not None else "",
  1168. mp if mp is not None else ""))
  1169. self._csv.flush()
  1170. except Exception:
  1171. pass
  1172. # ---- 统计
  1173. def _seg(self) -> List[Tuple[float, int, float]]:
  1174. return [s for s in self.samples if s[0] >= self._seg_start]
  1175. def rate_1h(self, now: float) -> Optional[float]:
  1176. pts = [s for s in self.samples if now - s[0] <= self.window * 60]
  1177. if len(pts) < 2:
  1178. return None
  1179. dt = pts[-1][0] - pts[0][0]
  1180. dv = pts[-1][1] - pts[0][1]
  1181. if dt < 20 or dv < 0:
  1182. return None
  1183. return dv * 3600.0 / dt
  1184. def avg_1h(self) -> Optional[float]:
  1185. seg = self._seg()
  1186. if len(seg) < 2:
  1187. return None
  1188. dt = seg[-1][0] - seg[0][0]
  1189. dv = seg[-1][1] - seg[0][1]
  1190. if dt < 60 or dv < 0:
  1191. return None
  1192. return dv * 3600.0 / dt
  1193. def total_exp(self) -> Optional[float]:
  1194. if not self.samples:
  1195. return None
  1196. _t, val, pct = self.samples[-1]
  1197. if pct <= 0.01:
  1198. return None
  1199. return val * 100.0 / pct
  1200. def eta(self, now: float) -> Optional[float]:
  1201. rate = self.rate_1h(now) or self.avg_1h()
  1202. total = self.total_exp()
  1203. if not rate or rate <= 0 or not total:
  1204. return None
  1205. remain = max(0.0, total - self.samples[-1][1])
  1206. return remain / rate * 3600.0
  1207. def close(self) -> None:
  1208. try:
  1209. if self._csv is not None and not self._csv.closed:
  1210. self._csv.close()
  1211. except Exception:
  1212. pass
  1213. # ---------------------------------------------------------------- 警报器
  1214. class Alerter:
  1215. def __init__(self, cfg: dict, popup_sink=None, quiet: bool = False):
  1216. self.cfg = cfg.get("alert", {})
  1217. self.popup_sink = popup_sink
  1218. self.quiet = quiet
  1219. self.count = 0
  1220. self.last_text = ""
  1221. self._wav = ensure_alarm_wav(ASSET_DIR / "alarm.wav",
  1222. float(self.cfg.get("volume", 0.9)))
  1223. self._sound_timer: Optional[threading.Timer] = None
  1224. self._beeping = False
  1225. self._beep_stop = threading.Event()
  1226. # ---- 声音
  1227. def _start_sound(self) -> None:
  1228. if self.quiet:
  1229. return
  1230. seconds = float(self.cfg.get("sound_seconds", 10))
  1231. try:
  1232. import winsound
  1233. if self._wav is not None:
  1234. winsound.PlaySound(str(self._wav),
  1235. winsound.SND_FILENAME | winsound.SND_ASYNC
  1236. | winsound.SND_LOOP)
  1237. else:
  1238. self._start_alt_beep()
  1239. except Exception:
  1240. self._start_alt_beep()
  1241. if self._sound_timer is not None:
  1242. self._sound_timer.cancel()
  1243. self._sound_timer = threading.Timer(seconds, self.stop_sound)
  1244. self._sound_timer.daemon = True
  1245. self._sound_timer.start()
  1246. def _start_alt_beep(self) -> None:
  1247. """wav 放不出来时,退化成系统蜂鸣。"""
  1248. if self._beeping:
  1249. return
  1250. self._beeping = True
  1251. self._beep_stop.clear()
  1252. def _loop():
  1253. try:
  1254. import winsound
  1255. while not self._beep_stop.is_set():
  1256. winsound.Beep(1000, 300)
  1257. winsound.Beep(700, 300)
  1258. except Exception:
  1259. pass
  1260. self._beeping = False
  1261. threading.Thread(target=_loop, daemon=True).start()
  1262. def stop_sound(self) -> None:
  1263. try:
  1264. import winsound
  1265. winsound.PlaySound(None, 0)
  1266. except Exception:
  1267. pass
  1268. self._beep_stop.set()
  1269. if self._sound_timer is not None:
  1270. self._sound_timer.cancel()
  1271. self._sound_timer = None
  1272. # ---- 触发
  1273. def fire(self, score: float, name: str, frame: Optional[np.ndarray] = None,
  1274. manual: bool = False, per: Optional[Dict[str, dict]] = None,
  1275. hits: int = 0) -> None:
  1276. self.count += 1
  1277. stamp = time.strftime("%H:%M:%S")
  1278. self.last_text = stamp
  1279. log("%s检测到测谎仪 相似度=%.3f 模板=%s 命中 %d/%d 个模板%s"
  1280. % ("【测试】" if manual else "⚠ ", score, name, hits,
  1281. len(per or {}), " (手动测试)" if manual else ""))
  1282. if self.cfg.get("save_snapshot", True) and frame is not None and not manual:
  1283. self._save_snapshot(frame, per, name, hits)
  1284. if self.cfg.get("bring_to_front", True) and not manual:
  1285. self._focus_game()
  1286. if self.cfg.get("sound", True):
  1287. self._start_sound()
  1288. if self.cfg.get("voice", False) and not self.quiet:
  1289. speak_async("注意,测谎仪出现,请立刻回到游戏")
  1290. if self.cfg.get("popup", True) and self.popup_sink is not None:
  1291. self.popup_sink({
  1292. "score": score, "name": name, "time": stamp,
  1293. "seconds": float(self.cfg.get("popup_seconds", 12)),
  1294. "manual": manual,
  1295. })
  1296. def _focus_game(self) -> None:
  1297. titles = CONFIG.get("game_window_titles", DEFAULT_CONFIG["game_window_titles"])
  1298. hwnd, _rect = find_game_window(titles)
  1299. if hwnd:
  1300. force_foreground(hwnd)
  1301. flash_window(hwnd)
  1302. else:
  1303. log("没找到游戏窗口,跳过切前台")
  1304. def _save_snapshot(self, frame: np.ndarray, per: Optional[Dict[str, dict]] = None,
  1305. name: str = "", hits: int = 0) -> None:
  1306. try:
  1307. LOG_DIR.mkdir(parents=True, exist_ok=True)
  1308. path = LOG_DIR / ("hit_%s.png" % time.strftime("%Y%m%d_%H%M%S"))
  1309. # 把匹配到的位置框出来,事后一眼看出它是认哪块画面认错的
  1310. img = annotate(frame, per or {},
  1311. float(CONFIG.get("threshold", 0.75)), winner=name)
  1312. imwrite(path, img)
  1313. shots = sorted(LOG_DIR.glob("hit_*.png"))
  1314. for old in shots[:-40]:
  1315. try:
  1316. old.unlink()
  1317. except Exception:
  1318. pass
  1319. except Exception:
  1320. pass
  1321. # ---------------------------------------------------------------- 运行时状态
  1322. CONFIG: dict = dict(DEFAULT_CONFIG)
  1323. class Stats:
  1324. def __init__(self):
  1325. self.fps = 0.0
  1326. self.score = 0.0
  1327. self.template = ""
  1328. self.region = (0, 0, 0, 0)
  1329. self.frames = 0
  1330. self.last_alert = 0.0
  1331. self.alerts = 0
  1332. self.paused = False
  1333. self.error = ""
  1334. # 游戏窗口状态:ok = 正常;min = 最小化了;none = 没找到;screen = 监控整屏
  1335. self.game = "none"
  1336. # 血蓝经验(读不到就是 None / 0)
  1337. self.hp = 0
  1338. self.hp_max = 0
  1339. self.mp = 0
  1340. self.mp_max = 0
  1341. self.exp = 0
  1342. self.exp_pct = 0.0
  1343. self.exp_rate = None # 实时 1H
  1344. self.exp_avg = None # 平均 1H
  1345. self.exp_eta = None # 预计升级还要多少秒
  1346. self.exp_total = None # 当前等级一共要多少经验
  1347. self.hp_alerts = 0
  1348. self.last_hp_alert = 0.0
  1349. # ---------------------------------------------------------------- 监控线程
  1350. def build_matcher(cfg: dict, items: List[Template], scales=None) -> Matcher:
  1351. return Matcher(items,
  1352. list(scales) if scales else (cfg.get("scales") or [1.0]),
  1353. float(cfg.get("threshold", 0.70)),
  1354. float(cfg.get("scale_down", 2.0)))
  1355. class Watcher(threading.Thread):
  1356. def __init__(self, cfg: dict, store: TemplateStore, alerter: Alerter,
  1357. stats: Stats, region_override=None, hud_alert=None, aim=None):
  1358. super().__init__(daemon=True, name="lie-watcher")
  1359. self.cfg = cfg
  1360. self.store = store
  1361. # 平时只查「画面跟模板一样大」这一档,最省 CPU;
  1362. # 万一你的画面缩放不一样,宽范围扫描会把它找出来并记住
  1363. self.scales = list(cfg.get("scales") or [1.0])
  1364. self.wide_scales = list(cfg.get("scales_wide") or [])
  1365. # 自动适应画面缩放:没命中时隔一阵子用宽档扫一遍,扫到就记住(并写进配置)
  1366. self.auto_scale = bool(cfg.get("auto_scale", True))
  1367. self.rescan_every = max(5, int(cfg.get("rescan_every", 40)))
  1368. self.scale_from_hud = bool(cfg.get("scale_from_hud", True))
  1369. self._since_wide = 0
  1370. self.matcher = build_matcher(cfg, store.items, self.scales)
  1371. self.alerter = alerter
  1372. self.stats = stats
  1373. self.region_override = region_override
  1374. self.aim = aim # AimAssistController,测谎报警后跟红准星
  1375. self._stop = threading.Event()
  1376. self._last_seen = 0.0
  1377. self._last_alert = 0.0
  1378. self._snooze_until = 0.0
  1379. self._hwnd = 0
  1380. self._hwnd_at = 0.0
  1381. self._grabber = ScreenGrabber()
  1382. self._frame_times: List[float] = []
  1383. self._confirm_streak = 0
  1384. self._ui_scale = float((self.scales or [1.0])[0])
  1385. self._scale_probed = False
  1386. self._last_client_size = (0, 0)
  1387. # 血蓝:读游戏底部那条 HUD
  1388. self.hud = None
  1389. if cfg.get("hud", {}).get("enabled", True):
  1390. reader = HudReader()
  1391. if reader.ready:
  1392. self.hud = reader
  1393. else:
  1394. log("templates/hud 里没有字形模板,血量/经验功能关闭")
  1395. self.hud_alert = hud_alert
  1396. # 经验统计
  1397. self.exp = ExpTrack(cfg) if cfg.get("exp", {}).get("enabled") else None
  1398. self._hud_at = 0.0
  1399. # ---- 外部控制
  1400. def stop(self) -> None:
  1401. self._stop.set()
  1402. def snooze(self, seconds: float) -> None:
  1403. self._snooze_until = time.time() + seconds
  1404. def apply_scale(self, scales: List[float], auto: bool) -> None:
  1405. """设置页改了缩放:立刻换一套档位重新查,不用重启。"""
  1406. new = [float(s) for s in (scales or [1.0])]
  1407. auto = bool(auto)
  1408. changed = (new != self.scales) or (auto != self.auto_scale)
  1409. self.scales = new
  1410. self.auto_scale = auto
  1411. self._ui_scale = float(new[len(new) // 2] if new else 1.0)
  1412. if changed:
  1413. self.matcher = build_matcher(self.cfg, self.store.items, self.scales)
  1414. self._since_wide = 0
  1415. self._scale_probed = False
  1416. log("缩放档位已改为 %s%s"
  1417. % (["x%.2f" % s for s in self.scales],
  1418. "(自动适应)" if self.auto_scale else "(固定)"))
  1419. self.alerter.stop_sound()
  1420. def test_alert(self) -> None:
  1421. self.alerter.fire(1.0, "手动测试", manual=True)
  1422. if self.aim is not None:
  1423. self.aim.trigger(manual=True)
  1424. def aim_region(self) -> Optional[Tuple[int, int, int, int]]:
  1425. """瞄准用的游戏客户区屏幕矩形;找不到游戏就返回 None。"""
  1426. titles = self.cfg.get("game_window_titles", DEFAULT_CONFIG["game_window_titles"])
  1427. if self._hwnd:
  1428. try:
  1429. x, y, w, h = client_rect(self._hwnd)
  1430. if w >= 320 and h >= 240:
  1431. return (int(x), int(y), int(w), int(h))
  1432. except Exception:
  1433. self._hwnd = 0
  1434. hwnd, rect = find_game_window(titles)
  1435. if hwnd and rect:
  1436. self._hwnd = hwnd
  1437. return (int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3]))
  1438. return None
  1439. # ---- 区域
  1440. def _region(self) -> Tuple[int, int, int, int]:
  1441. titles = self.cfg.get("game_window_titles", DEFAULT_CONFIG["game_window_titles"])
  1442. if self.region_override:
  1443. self.stats.game = "screen"
  1444. return clamp_region(self.region_override)
  1445. if self.cfg.get("capture") == "screen":
  1446. self.stats.game = "screen"
  1447. return clamp_region(virtual_screen())
  1448. now = time.time()
  1449. if now - self._hwnd_at > 2.0 or not self._hwnd:
  1450. self._hwnd, _rect = find_game_window(titles)
  1451. self._hwnd_at = now
  1452. if self._hwnd:
  1453. try:
  1454. x, y, w, h = client_rect(self._hwnd)
  1455. if w >= 320 and h >= 240:
  1456. self.stats.game = "ok"
  1457. return clamp_region((x, y, w, h))
  1458. except Exception:
  1459. self._hwnd = 0
  1460. # 没找到游戏窗口:要么最小化了,要么根本没开
  1461. self.stats.game = ("min" if game_window_minimized(titles) else "none")
  1462. self.stats.hp = self.stats.hp_max = 0
  1463. self.stats.mp = self.stats.mp_max = 0
  1464. self.stats.exp = 0.0
  1465. self.stats.exp_pct = 0.0
  1466. return clamp_region(virtual_screen())
  1467. # ---- 血蓝 / 经验
  1468. def _update_hud(self, gray: np.ndarray, now: float) -> None:
  1469. st = self.stats
  1470. if st.game != "ok":
  1471. # 画面不是游戏客户区(没开 / 最小化 / 整屏兜底)就别拿旧数字乱报警
  1472. return
  1473. vals = self.hud.read(gray, ui_scale=self._ui_scale)
  1474. hp, mp, exp = vals.get("hp"), vals.get("mp"), vals.get("exp")
  1475. if hp and hp[1] > 0:
  1476. st.hp, st.hp_max = hp[0], hp[1]
  1477. if mp and mp[1] > 0:
  1478. st.mp, st.mp_max = mp[0], mp[1]
  1479. if exp:
  1480. st.exp, st.exp_pct = exp[0], exp[1]
  1481. if self.exp is not None and exp:
  1482. self.exp.feed(now, exp[0], exp[1], st.hp or None, st.mp or None)
  1483. st.exp_rate = self.exp.rate_1h(now)
  1484. st.exp_avg = self.exp.avg_1h()
  1485. st.exp_eta = self.exp.eta(now)
  1486. st.exp_total = self.exp.total_exp()
  1487. if self.hud_alert is not None:
  1488. hp_pct = (st.hp * 100.0 / st.hp_max) if st.hp_max else None
  1489. mp_pct = (st.mp * 100.0 / st.mp_max) if st.mp_max else None
  1490. before = self.hud_alert.count
  1491. self.hud_alert.check(now, hp_pct, mp_pct)
  1492. if self.hud_alert.count != before:
  1493. st.hp_alerts = self.hud_alert.count
  1494. st.last_hp_alert = now
  1495. def _remember_scales(self, center: float, reason: str) -> None:
  1496. """把推算出的 UI 缩放写成三档附近搜索,并持久化。"""
  1497. center = float(center)
  1498. new_scales = sorted({round(center * k, 3) for k in (0.96, 1.0, 1.04)})
  1499. self._ui_scale = center
  1500. if new_scales == self.scales:
  1501. return
  1502. self.scales = new_scales
  1503. self.matcher = build_matcher(self.cfg, self.store.items, self.scales)
  1504. try:
  1505. self.cfg["scales"] = new_scales
  1506. save_config(self.cfg)
  1507. except Exception:
  1508. pass
  1509. log("画面缩放和模板不一样,已按 x%.2f 调整档位:%s(%s,已记住)"
  1510. % (center, self.scales, reason))
  1511. def _probe_ui_scale(self, gray: np.ndarray, force: bool = False) -> None:
  1512. """启动后 / 窗口尺寸变化时,用 HUD 标签推一把 UI 缩放。"""
  1513. if not self.auto_scale or not self.scale_from_hud:
  1514. return
  1515. if self.hud is None or not self.hud.labels:
  1516. return
  1517. if self._scale_probed and not force:
  1518. return
  1519. wide = list(self.cfg.get("scales_wide") or self.wide_scales or [])
  1520. est = estimate_ui_scale(gray, self.hud.labels, wide or None)
  1521. self._scale_probed = True
  1522. if est is None:
  1523. return
  1524. if abs(est - self._ui_scale) >= 0.04 or abs(est - 1.0) >= 0.06:
  1525. self._remember_scales(est, "按底部HP标签推算")
  1526. else:
  1527. self._ui_scale = est
  1528. def _judge(self, hit, per, threshold: float):
  1529. """返回 (confirmed, hard_hits_in_cluster)。"""
  1530. min_hits = max(1, int(self.cfg.get("min_hits", 2)))
  1531. strong = float(self.cfg.get("strong_threshold", 0.92))
  1532. require_layout = bool(self.cfg.get("require_layout", True))
  1533. pair_avg = float(self.cfg.get("pair_avg_threshold", 0.82))
  1534. clustered = cluster_hits(per, threshold) if require_layout \
  1535. else _hit_items(per, threshold)
  1536. hits = sum(1 for _, v in clustered
  1537. if float(v.get("score", 0.0)) >= threshold)
  1538. ok = is_confirmed(hit, per, threshold, min_hits, strong,
  1539. require_layout=require_layout, pair_avg=pair_avg)
  1540. return ok, hits
  1541. # ---- 主循环
  1542. def run(self) -> None:
  1543. interval = 1.0 / max(1.0, float(self.cfg.get("max_fps", 6)))
  1544. repeat = float(self.cfg.get("alert_repeat_seconds", 15))
  1545. threshold = float(self.cfg.get("threshold", 0.75))
  1546. log("开始监控:%d 个模板,阈值 %.2f,目标 %d 帧/秒"
  1547. % (len(self.store.items), threshold, int(1 / interval)))
  1548. # 想看每帧到底花多少时间,就设环境变量 LIE_TRACE=1 再运行
  1549. trace = bool(os.environ.get("LIE_TRACE"))
  1550. if trace:
  1551. log("调试模式:逐帧打印抓屏/识别耗时")
  1552. while not self._stop.is_set():
  1553. # 帧率/阈值每帧现读:设置页改完不用重启就生效
  1554. interval = 1.0 / max(1.0, float(self.cfg.get("max_fps", 6)))
  1555. threshold = float(self.cfg.get("threshold", 0.75))
  1556. need_frames = max(1, int(self.cfg.get("confirm_frames", 2)))
  1557. started = time.perf_counter()
  1558. if self.stats.paused:
  1559. time.sleep(0.15)
  1560. continue
  1561. if self.store.maybe_reload():
  1562. self.matcher = build_matcher(self.cfg, self.store.items,
  1563. self.scales)
  1564. log("模板已更新:%d 个" % len(self.store.items))
  1565. region = self._region()
  1566. self.stats.region = region
  1567. # 没游戏窗口 / 游戏最小化了就待机:整屏画面里什么都有,
  1568. # 拿它去认模板特别容易误报(浏览器工具栏那种就是),干脆不认。
  1569. if self.stats.game in ("none", "min"):
  1570. self.stats.score = 0.0
  1571. self._confirm_streak = 0
  1572. time.sleep(max(interval, 0.4))
  1573. continue
  1574. t0 = time.perf_counter()
  1575. gray = self._grabber.grab_gray(*region)
  1576. t1 = time.perf_counter()
  1577. if gray is None:
  1578. self.stats.error = "抓屏失败"
  1579. time.sleep(0.5)
  1580. continue
  1581. client_size = (int(region[2]), int(region[3]))
  1582. if client_size != self._last_client_size:
  1583. # 分辨率/窗口大小变了:重新用 HUD 推缩放
  1584. if self._last_client_size != (0, 0):
  1585. self._scale_probed = False
  1586. self._last_client_size = client_size
  1587. self._probe_ui_scale(gray)
  1588. hit, per = self.matcher.match(gray)
  1589. t2 = time.perf_counter()
  1590. if self.hud is not None:
  1591. self._update_hud(gray, time.time())
  1592. self._since_wide += 1
  1593. confirmed, hits = self._judge(hit, per, threshold)
  1594. # 没确认命中时,隔一阵子把缩放档位放宽扫一遍:
  1595. # 既兜住「画面缩放跟模板不一样」的情况,扫到了就记住,以后按这个档位查
  1596. if (not confirmed and self.auto_scale
  1597. and self._since_wide >= self.rescan_every
  1598. and len(self.wide_scales) > 1):
  1599. self._since_wide = 0
  1600. wide = build_matcher(self.cfg, self.store.items, self.wide_scales)
  1601. wh, wper = wide.match(gray, early_exit=False)
  1602. if wh.score >= threshold * 0.9:
  1603. hit, per = wh, wper
  1604. confirmed, hits = self._judge(hit, per, threshold)
  1605. if (wh.score >= max(threshold, 0.80)
  1606. and abs(wh.scale - self._ui_scale) > 0.06):
  1607. self._remember_scales(wh.scale, "宽范围扫描")
  1608. self.stats.score = hit.score
  1609. self.stats.template = hit.name
  1610. self.stats.frames += 1
  1611. if trace:
  1612. log("帧 %d:区域 %dx%d 抓屏 %.0fms 识别 %.0fms 分数 %.3f 命中 %d/%d%s"
  1613. % (self.stats.frames, region[2], region[3],
  1614. (t1 - t0) * 1000.0, (t2 - t1) * 1000.0, hit.score,
  1615. hits, len(per),
  1616. (" ← " + hit.name) if confirmed else ""))
  1617. if confirmed:
  1618. self._confirm_streak += 1
  1619. else:
  1620. self._confirm_streak = 0
  1621. if confirmed and self._confirm_streak >= need_frames:
  1622. now = time.time()
  1623. gap = now - self._last_seen if self._last_seen else 1e9
  1624. self._last_seen = now
  1625. due = (self._last_alert == 0.0 or gap >= repeat
  1626. or (now - self._last_alert) >= repeat)
  1627. if due and now >= self._snooze_until:
  1628. self._last_alert = now
  1629. self.stats.last_alert = now
  1630. self.stats.alerts += 1
  1631. self.alerter.fire(hit.score, hit.name, frame=gray,
  1632. per=per, hits=hits)
  1633. # 报警后立刻开 YOLO+ByteTrack,用 Interception 跟红准星
  1634. if self.aim is not None:
  1635. try:
  1636. self.aim.trigger(manual=False)
  1637. except Exception as exc:
  1638. log("启动瞄准失败:%s" % exc)
  1639. elif trace and hit.score >= threshold:
  1640. log("未确认报警:命中 %d 连续 %d/%d(%s %.3f)"
  1641. % (hits, self._confirm_streak, need_frames,
  1642. hit.name, hit.score))
  1643. elapsed = time.perf_counter() - started
  1644. # 单帧真实占用 = 干活的时间 + 为了限速而睡的时间
  1645. total = elapsed if elapsed > interval else interval
  1646. self._frame_times.append(total)
  1647. if len(self._frame_times) > 20:
  1648. self._frame_times.pop(0)
  1649. avg = sum(self._frame_times) / len(self._frame_times)
  1650. self.stats.fps = 1.0 / avg if avg > 0 else 0.0
  1651. wait = interval - elapsed
  1652. if wait > 0:
  1653. time.sleep(wait)
  1654. # ---------------------------------------------------------------- 界面
  1655. class StatusApp:
  1656. """状态小窗 + 红色提醒窗。Tk 必须在主线程。"""
  1657. def __init__(self, ctl: "Controller"):
  1658. import tkinter as tk
  1659. self.tk = tk
  1660. self.ctl = ctl
  1661. self.popup = None
  1662. self._popup_after = None
  1663. self._popup_info = None
  1664. self.toast = None
  1665. self._toast_after = None
  1666. self.exp_win = None
  1667. self._exp_texts = None
  1668. self._exp_canvas = None
  1669. self.settings = None
  1670. root = tk.Tk()
  1671. self.root = root
  1672. root.title(APP_NAME)
  1673. root.resizable(False, False)
  1674. root.configure(bg="#1f1f1f")
  1675. root.protocol("WM_DELETE_WINDOW", self._on_quit)
  1676. sw = root.winfo_screenwidth()
  1677. sh = root.winfo_screenheight()
  1678. W, H = 340, 224
  1679. x, y = max(0, sw - W - 30), max(0, sh - H - 80)
  1680. # 优先摆在游戏窗口右边/下边,尽量别挡住游戏画面
  1681. try:
  1682. hwnd, _r = find_game_window(ctl.cfg.get("game_window_titles", []))
  1683. if hwnd:
  1684. gx, gy, gw, gh = client_rect(hwnd)
  1685. rx = min(max(0, gx + gw - W), sw - W - 10)
  1686. if gw > 200 and gx + gw + W + 8 <= sw:
  1687. x, y = gx + gw + 6, gy # 游戏右边
  1688. elif gw > 200 and gy + gh + H + 8 <= sh:
  1689. x, y = rx, gy + gh + 6 # 游戏下边
  1690. elif gw > 200 and gy - H - 8 >= 0:
  1691. x, y = rx, gy - H - 8 # 游戏上边
  1692. except Exception:
  1693. pass
  1694. root.geometry("%dx%d+%d+%d" % (W, H, x, y))
  1695. try:
  1696. root.attributes("-topmost", bool(ctl.cfg.get("status_on_top", False)))
  1697. except Exception:
  1698. pass
  1699. font = ("Microsoft YaHei UI", 10)
  1700. title = tk.Label(root, text="冒险岛 · 测谎仪提醒", bg="#1f1f1f", fg="#f0c040",
  1701. font=("Microsoft YaHei UI", 12, "bold"))
  1702. title.pack(pady=(10, 4))
  1703. # 右上角那颗齿轮:点开设置页
  1704. self.gear = tk.Label(root, text="⚙", bg="#1f1f1f", fg="#8a8a8a",
  1705. font=("Segoe UI Symbol", 13), cursor="hand2")
  1706. self.gear.place(relx=1.0, x=-10, y=6, anchor="ne")
  1707. self.gear.bind("<Button-1>", lambda _e: self._open_settings())
  1708. self.gear.bind("<Enter>", lambda _e: self.gear.config(fg="#f0c040"))
  1709. self.gear.bind("<Leave>", lambda _e: self.gear.config(fg="#8a8a8a"))
  1710. self.lbl_state = tk.Label(root, text="正在启动…", bg="#1f1f1f", fg="#7ed321",
  1711. font=("Microsoft YaHei UI", 11, "bold"))
  1712. self.lbl_state.pack()
  1713. self.lbl_info = tk.Label(root, text="", bg="#1f1f1f", fg="#cccccc", font=font,
  1714. justify="center")
  1715. self.lbl_info.pack(pady=(2, 6))
  1716. bar = tk.Frame(root, bg="#1f1f1f")
  1717. bar.pack()
  1718. self.btn_pause = tk.Button(bar, text="暂停", width=6, command=self._toggle_pause,
  1719. font=font)
  1720. self.btn_pause.pack(side="left", padx=3)
  1721. tk.Button(bar, text="测试", width=6, command=self._test,
  1722. font=font).pack(side="left", padx=3)
  1723. self.btn_exp = tk.Button(bar, text="经验", width=6, command=self._toggle_exp,
  1724. font=font)
  1725. self.btn_exp.pack(side="left", padx=3)
  1726. tk.Button(bar, text="退出", width=5, command=self._on_quit,
  1727. font=font).pack(side="left", padx=3)
  1728. self._poll()
  1729. # 开了经验统计就把统计小窗一起打开
  1730. exp_cfg = ctl.cfg.get("exp", {})
  1731. if exp_cfg.get("enabled") and exp_cfg.get("window", True):
  1732. self.root.after(600, self._open_exp_window)
  1733. # ---- 轮询
  1734. def _poll(self) -> None:
  1735. st = self.ctl.stats
  1736. try:
  1737. while True:
  1738. ev = self.ctl.events.get_nowait()
  1739. if ev[0] == "alert":
  1740. self._show_popup(ev[1])
  1741. elif ev[0] == "toast":
  1742. self._show_toast(ev[1])
  1743. except queue.Empty:
  1744. pass
  1745. if st.paused:
  1746. self.lbl_state.config(text="⏸ 已暂停", fg="#f0c040")
  1747. elif st.error:
  1748. self.lbl_state.config(text="⚠ " + st.error, fg="#ff5555")
  1749. elif st.game == "none":
  1750. self.lbl_state.config(text="○ 等游戏窗口…", fg="#f0c040")
  1751. elif st.game == "min":
  1752. self.lbl_state.config(text="○ 游戏最小化了", fg="#f0c040")
  1753. else:
  1754. self.lbl_state.config(text="● 监控中", fg="#7ed321")
  1755. lines = []
  1756. if st.hp_max > 0:
  1757. hp_pct = st.hp * 100.0 / st.hp_max
  1758. mp_txt = ""
  1759. if st.mp_max > 0:
  1760. mp_txt = " MP %.0f%%" % (st.mp * 100.0 / st.mp_max)
  1761. lines.append("HP %.0f%% (%d/%d)%s" % (hp_pct, st.hp, st.hp_max, mp_txt))
  1762. if st.exp_pct > 0:
  1763. bits = ["EXP %.2f%%" % st.exp_pct]
  1764. if st.exp_rate:
  1765. bits.append("1H %s" % fmt_exp(st.exp_rate))
  1766. if st.exp_eta:
  1767. bits.append("升级约 %s" % fmt_duration(st.exp_eta))
  1768. lines.append(" · ".join(bits))
  1769. last = ("--:--:--" if not st.last_alert
  1770. else time.strftime("%H:%M:%S", time.localtime(st.last_alert)))
  1771. tail = ["%.1f 帧/秒" % st.fps, "%.2f" % st.score,
  1772. "测谎 %d" % st.alerts]
  1773. if st.hp_alerts:
  1774. tail.append("低血 %d" % st.hp_alerts)
  1775. tail.append(last)
  1776. lines.append(" · ".join(tail))
  1777. self.lbl_info.config(text="\n".join(lines))
  1778. self._update_exp_window()
  1779. self.root.after(200, self._poll)
  1780. # ---- 按钮
  1781. def _toggle_pause(self) -> None:
  1782. self.ctl.stats.paused = not self.ctl.stats.paused
  1783. self.btn_pause.config(text="继续" if self.ctl.stats.paused else "暂停")
  1784. def _open_settings(self) -> None:
  1785. if self.settings is not None:
  1786. try:
  1787. self.settings.top.deiconify()
  1788. self.settings.top.lift()
  1789. return
  1790. except Exception:
  1791. self.settings = None
  1792. try:
  1793. self.settings = SettingsWindow(self.ctl, self.root)
  1794. except Exception as exc:
  1795. log("打开设置失败:%s" % exc)
  1796. def _test(self) -> None:
  1797. self.ctl.watcher.test_alert()
  1798. def _on_quit(self) -> None:
  1799. try:
  1800. self.ctl.stop()
  1801. finally:
  1802. self.root.destroy()
  1803. # ---- 红色提醒窗
  1804. def _show_popup(self, info: dict) -> None:
  1805. tk = self.tk
  1806. if self.popup is not None and self.popup.winfo_exists():
  1807. try:
  1808. self.popup.lift()
  1809. self.popup.attributes("-topmost", True)
  1810. if self._popup_after is not None:
  1811. self.popup.after_cancel(self._popup_after)
  1812. except Exception:
  1813. pass
  1814. else:
  1815. win = tk.Toplevel(self.root)
  1816. win.overrideredirect(True)
  1817. win.attributes("-topmost", True)
  1818. win.configure(bg="#c00000", cursor="hand2")
  1819. width, height = 430, 186
  1820. sw = self.root.winfo_screenwidth()
  1821. win.geometry("%dx%d+%d+%d" % (width, height,
  1822. max(0, (sw - width) // 2), 28))
  1823. box = tk.Frame(win, bg="#c00000")
  1824. box.pack(expand=True, fill="both", padx=14, pady=10)
  1825. tk.Label(box, text="⚠ 测谎仪!", bg="#c00000", fg="#ffffff",
  1826. font=("Microsoft YaHei UI", 26, "bold")).pack(pady=(4, 0))
  1827. tk.Label(box, text="快回游戏,把鼠标放到图形上", bg="#c00000",
  1828. fg="#ffe9a8", font=("Microsoft YaHei UI", 13, "bold")).pack(pady=(2, 4))
  1829. self._lbl_sub = tk.Label(box, text="", bg="#c00000", fg="#ffd0d0",
  1830. font=("Microsoft YaHei UI", 9))
  1831. self._lbl_sub.pack()
  1832. tk.Label(box, text="点一下这里关掉", bg="#c00000", fg="#ffb0b0",
  1833. font=("Microsoft YaHei UI", 8)).pack(pady=(4, 0))
  1834. for widget in (win, box) + tuple(box.winfo_children()):
  1835. widget.bind("<Button-1>", lambda _e: self._dismiss_popup())
  1836. self.popup = win
  1837. text = "%s · 相似度 %.2f · %s" % (
  1838. "手动测试" if info.get("manual") else "已提醒", info.get("score", 0.0),
  1839. info.get("time", ""))
  1840. try:
  1841. self._lbl_sub.config(text=text)
  1842. except Exception:
  1843. pass
  1844. seconds = max(3.0, float(info.get("seconds", 12)))
  1845. self._popup_after = self.popup.after(int(seconds * 1000), self._dismiss_popup)
  1846. def _dismiss_popup(self) -> None:
  1847. if self.popup is None:
  1848. return
  1849. try:
  1850. self.popup.destroy()
  1851. except Exception:
  1852. pass
  1853. self.popup = None
  1854. self._popup_after = None
  1855. snooze = float(self.ctl.cfg.get("alert", {}).get("snooze_seconds", 60))
  1856. self.ctl.watcher.snooze(snooze)
  1857. # ---- 低血/低蓝的小提示条(不抢焦点、不切窗口)
  1858. def _show_toast(self, info: dict) -> None:
  1859. tk = self.tk
  1860. if self.toast is not None and self.toast.winfo_exists():
  1861. try:
  1862. self.toast.destroy()
  1863. except Exception:
  1864. pass
  1865. self.toast = None
  1866. win = tk.Toplevel(self.root)
  1867. win.overrideredirect(True)
  1868. win.attributes("-topmost", True)
  1869. win.configure(bg="#7a3b00", cursor="hand2")
  1870. w, h = 300, 84
  1871. try:
  1872. x = self.root.winfo_x()
  1873. y = self.root.winfo_y() + self.root.winfo_height() + 8
  1874. # 经验统计小窗也贴在下面时,提示条让到它下方,免得互相盖住
  1875. if self.exp_win is not None and self.exp_win.winfo_exists():
  1876. y = max(y, self.exp_win.winfo_y() + self.exp_win.winfo_height() + 40)
  1877. except Exception:
  1878. x, y = 40, 40
  1879. sw, sh = win.winfo_screenwidth(), win.winfo_screenheight()
  1880. x = min(max(0, x), max(0, sw - w - 10))
  1881. y = min(max(0, y), max(0, sh - h - 50))
  1882. win.geometry("%dx%d+%d+%d" % (w, h, x, y))
  1883. tk.Label(win, text="⚠ " + str(info.get("title", "")), bg="#7a3b00",
  1884. fg="#ffd9a8",
  1885. font=("Microsoft YaHei UI", 13, "bold")).pack(pady=(10, 2))
  1886. tk.Label(win, text=str(info.get("text", "")), bg="#7a3b00", fg="#ffbf80",
  1887. font=("Microsoft YaHei UI", 9)).pack()
  1888. for widget in (win,) + tuple(win.winfo_children()):
  1889. widget.bind("<Button-1>", lambda _e: self._dismiss_toast())
  1890. self.toast = win
  1891. self._toast_after = win.after(
  1892. int(max(2.0, float(info.get("seconds", 6))) * 1000), self._dismiss_toast)
  1893. def _dismiss_toast(self) -> None:
  1894. if self.toast is None:
  1895. return
  1896. try:
  1897. self.toast.destroy()
  1898. except Exception:
  1899. pass
  1900. self.toast = None
  1901. self._toast_after = None
  1902. # ---- 经验统计小窗
  1903. def _toggle_exp(self) -> None:
  1904. if self.exp_win is not None:
  1905. try:
  1906. if self.exp_win.winfo_exists():
  1907. self.exp_win.destroy()
  1908. self.exp_win = None
  1909. return
  1910. except Exception:
  1911. pass
  1912. self.exp_win = None
  1913. self._open_exp_window()
  1914. def _open_exp_window(self) -> None:
  1915. tk = self.tk
  1916. win = tk.Toplevel(self.root)
  1917. win.title("经验统计")
  1918. win.resizable(False, False)
  1919. win.configure(bg="#1f1f1f")
  1920. w, h = 396, 268
  1921. try:
  1922. # 优先贴在状态窗右侧,其次下方(右边和下方都在游戏画面之外),
  1923. # 最后才放左边——放左边会盖住游戏区域。
  1924. sw, sh = win.winfo_screenwidth(), win.winfo_screenheight()
  1925. x = self.root.winfo_x() + self.root.winfo_width() + 8
  1926. y = self.root.winfo_y()
  1927. if x + w > sw:
  1928. x = self.root.winfo_x()
  1929. y = self.root.winfo_y() + self.root.winfo_height() + 8
  1930. if y + h > sh:
  1931. y = max(0, sh - h - 10)
  1932. if x + w > sw:
  1933. x = max(0, sw - w - 10)
  1934. except Exception:
  1935. x, y = 40, 40
  1936. win.geometry("%dx%d+%d+%d" % (w, h, x, y))
  1937. font = ("Microsoft YaHei UI", 10)
  1938. head = tk.Frame(win, bg="#1f1f1f")
  1939. head.pack(fill="x", padx=12, pady=(10, 2))
  1940. tk.Label(head, text="经验统计", bg="#1f1f1f", fg="#f0c040",
  1941. font=("Microsoft YaHei UI", 12, "bold")).pack(side="left")
  1942. tk.Label(head, text="数据存 logs\\exp_*.csv", bg="#1f1f1f", fg="#777777",
  1943. font=("Microsoft YaHei UI", 8)).pack(side="right")
  1944. grid = tk.Frame(win, bg="#1f1f1f")
  1945. grid.pack(fill="x", padx=12)
  1946. texts = {}
  1947. for i, (key, label) in enumerate((
  1948. ("now", "当前经验"), ("rate", "实时 1H"), ("avg", "平均 1H"),
  1949. ("remain", "这级还差"), ("eta", "预计升级"))):
  1950. tk.Label(grid, text=label, bg="#1f1f1f", fg="#999999", font=font,
  1951. anchor="w", width=8).grid(row=i // 2, column=(i % 2) * 2,
  1952. sticky="w", padx=(0, 2), pady=1)
  1953. lb = tk.Label(grid, text="--", bg="#1f1f1f", fg="#dddddd", font=font,
  1954. anchor="w", width=16)
  1955. lb.grid(row=i // 2, column=(i % 2) * 2 + 1, sticky="w", padx=(0, 10), pady=1)
  1956. texts[key] = lb
  1957. self._exp_texts = texts
  1958. cv = tk.Canvas(win, width=372, height=96, bg="#111111",
  1959. highlightthickness=0)
  1960. cv.pack(padx=12, pady=(8, 4))
  1961. self._exp_canvas = cv
  1962. tk.Label(win, text="最近 1 小时的实时 1H 经验走势", bg="#1f1f1f",
  1963. fg="#777777", font=("Microsoft YaHei UI", 8)).pack()
  1964. self.exp_win = win
  1965. def _update_exp_window(self) -> None:
  1966. if self.exp_win is None:
  1967. return
  1968. try:
  1969. if not self.exp_win.winfo_exists():
  1970. self.exp_win = None
  1971. return
  1972. except Exception:
  1973. self.exp_win = None
  1974. return
  1975. st = self.ctl.stats
  1976. texts = self._exp_texts or {}
  1977. remain = None
  1978. if st.exp_total and st.exp:
  1979. remain = max(0.0, st.exp_total - st.exp)
  1980. values = {
  1981. "now": "%s (%.2f%%)" % (fmt_exp(st.exp), st.exp_pct),
  1982. "rate": ("%s / 时" % fmt_exp(st.exp_rate)) if st.exp_rate else "--",
  1983. "avg": ("%s / 时" % fmt_exp(st.exp_avg)) if st.exp_avg else "--",
  1984. "remain": fmt_exp(remain),
  1985. "eta": fmt_duration(st.exp_eta),
  1986. }
  1987. for key, lb in texts.items():
  1988. try:
  1989. lb.config(text=values.get(key, "--"))
  1990. except Exception:
  1991. pass
  1992. if self._exp_canvas is not None:
  1993. try:
  1994. self._draw_chart(self._exp_canvas)
  1995. except Exception:
  1996. pass
  1997. def _draw_chart(self, cv) -> None:
  1998. W, H = 372, 96
  1999. cv.delete("all")
  2000. cv.create_rectangle(0, 0, W, H, fill="#111111", outline="")
  2001. for i in range(1, 4):
  2002. y = H * i / 4.0
  2003. cv.create_line(0, y, W, y, fill="#262626")
  2004. tracker = getattr(self.ctl.watcher, "exp", None)
  2005. hist = list(getattr(tracker, "rate_hist", []) or []) if tracker else []
  2006. now = time.time()
  2007. pts = [(t, v) for t, v in hist if now - t <= 3600]
  2008. if len(pts) < 2:
  2009. cv.create_text(W // 2, H // 2, text="再挂一会儿就有走势了",
  2010. fill="#777777", font=("Microsoft YaHei UI", 9))
  2011. return
  2012. t0 = max(now - 3600, pts[0][0])
  2013. span = max(60.0, pts[-1][0] - t0)
  2014. vmax = max(v for _t, v in pts) or 1.0
  2015. coords = []
  2016. for t, v in pts:
  2017. x = (t - t0) / span * (W - 10) + 5
  2018. y = H - 10 - (v / vmax) * (H - 26)
  2019. coords.extend((x, y))
  2020. cv.create_line(*coords, fill="#7ed321", width=2)
  2021. cv.create_text(6, 8, text="峰值 %s / 时" % fmt_exp(vmax), anchor="w",
  2022. fill="#9be36b", font=("Microsoft YaHei UI", 8))
  2023. def run(self) -> None:
  2024. self.root.mainloop()
  2025. # ---------------------------------------------------------------- 设置页
  2026. class SettingsWindow:
  2027. """齿轮按钮打开的设置页:勾一勾、改个数,保存就写回 config.json。"""
  2028. def __init__(self, ctl: "Controller", master):
  2029. import tkinter as tk
  2030. self.tk = tk
  2031. self.ctl = ctl
  2032. self.cfg = ctl.cfg
  2033. self.font = ("Microsoft YaHei UI", 9)
  2034. self.vars: Dict[str, object] = {}
  2035. alert = self.cfg.get("alert", {})
  2036. hp = self.cfg.get("hp_alert", {})
  2037. exp = self.cfg.get("exp", {})
  2038. top = tk.Toplevel(master)
  2039. self.top = top
  2040. top.title("设置")
  2041. top.configure(bg="#1f1f1f")
  2042. top.resizable(False, False)
  2043. top.transient(master)
  2044. try:
  2045. top.attributes("-topmost", True)
  2046. except Exception:
  2047. pass
  2048. top.protocol("WM_DELETE_WINDOW", self._close)
  2049. # ---- 测谎提醒
  2050. self._section("测谎提醒")
  2051. r = self._row()
  2052. self._check(r, "声音", "alert_sound", bool(alert.get("sound", True)))
  2053. self._label(r, "响")
  2054. self._spin(r, "alert_sound_seconds", alert.get("sound_seconds", 10),
  2055. 3, 120, 1, 4, "%.0f")
  2056. self._label(r, "秒 音量")
  2057. self._spin(r, "alert_volume", alert.get("volume", 0.9),
  2058. 0.1, 1.0, 0.1, 4, "%.2f")
  2059. r = self._row()
  2060. self._check(r, "红色大弹窗", "alert_popup", bool(alert.get("popup", True)))
  2061. self._label(r, "停留")
  2062. self._spin(r, "alert_popup_seconds", alert.get("popup_seconds", 12),
  2063. 3, 120, 1, 4, "%.0f")
  2064. self._label(r, "秒")
  2065. r = self._row()
  2066. self._check(r, "报警时切到游戏", "bring_to_front",
  2067. bool(alert.get("bring_to_front", True)))
  2068. self._label(r, " ")
  2069. self._check(r, "保存现场截图", "save_snapshot",
  2070. bool(alert.get("save_snapshot", True)))
  2071. r = self._row()
  2072. self._label(r, "相似度阈值", pad=(0, 2))
  2073. self._spin(r, "threshold", self.cfg.get("threshold", 0.75),
  2074. 0.5, 0.99, 0.01, 5, "%.2f")
  2075. self._label(r, " 至少")
  2076. self._spin(r, "min_hits", self.cfg.get("min_hits", 2), 1, 4, 1, 3, "%.0f")
  2077. self._label(r, "个模板 每秒")
  2078. self._spin(r, "max_fps", self.cfg.get("max_fps", 5), 1, 15, 1, 3, "%.0f")
  2079. self._label(r, "次")
  2080. r = self._row()
  2081. self._label(r, "连续确认", pad=(0, 2))
  2082. self._spin(r, "confirm_frames", self.cfg.get("confirm_frames", 2),
  2083. 1, 5, 1, 3, "%.0f")
  2084. self._label(r, "帧 ")
  2085. self._check(r, "布局校验(防误报)", "require_layout",
  2086. bool(self.cfg.get("require_layout", True)))
  2087. r = self._row()
  2088. self._check(r, "自动适应画面缩放", "auto_scale",
  2089. bool(self.cfg.get("auto_scale", True)))
  2090. self._label(r, " 固定 x")
  2091. cur_scale = float((self.cfg.get("scales") or [1.0])[0])
  2092. self._spin(r, "scale_value", cur_scale, 0.5, 2.0, 0.01, 5, "%.2f")
  2093. # ---- 血量 / 蓝量
  2094. self._section("血量 / 蓝量")
  2095. r = self._row()
  2096. self._check(r, "血量提醒", "hp_enabled", bool(hp.get("enabled", True)))
  2097. self._label(r, "低于")
  2098. self._spin(r, "hp_low", hp.get("low_pct", 30), 1, 95, 1, 3, "%.0f")
  2099. self._label(r, "% 回到")
  2100. self._spin(r, "hp_recover", hp.get("recover_pct", 35), 1, 99, 1, 3, "%.0f")
  2101. self._label(r, "% 停")
  2102. r = self._row()
  2103. self._check(r, "蓝量提醒", "mp_enabled", bool(hp.get("mp_enabled", True)))
  2104. self._label(r, "低于")
  2105. self._spin(r, "mp_low", hp.get("mp_low_pct", 10), 1, 95, 1, 3, "%.0f")
  2106. self._label(r, "% 回到")
  2107. self._spin(r, "mp_recover", hp.get("mp_recover_pct", 15), 1, 99, 1, 3, "%.0f")
  2108. self._label(r, "% 停")
  2109. r = self._row()
  2110. self._label(r, "重复提醒间隔", pad=(0, 2))
  2111. self._spin(r, "hp_repeat", hp.get("repeat_seconds", 30), 5, 300, 5, 4, "%.0f")
  2112. self._label(r, "秒 ")
  2113. self._check(r, "提示音", "hp_sound", bool(hp.get("sound", True)))
  2114. self._label(r, "音量")
  2115. self._spin(r, "hp_volume", hp.get("volume", 0.45), 0.1, 1.0, 0.1, 4, "%.2f")
  2116. # ---- 经验统计
  2117. self._section("经验统计")
  2118. r = self._row()
  2119. self._check(r, "记录经验", "exp_enabled", bool(exp.get("enabled", False)))
  2120. self._label(r, " ")
  2121. self._check(r, "打开统计小窗", "exp_window", bool(exp.get("window", True)))
  2122. r = self._row()
  2123. self._label(r, "采样间隔", pad=(0, 2))
  2124. self._spin(r, "exp_sample", exp.get("sample_seconds", 10), 5, 120, 5, 4, "%.0f")
  2125. self._label(r, "秒(越大越省 CPU)")
  2126. # ---- 瞄准(YOLO + Interception)
  2127. aim = self.cfg.get("aim_assist", {})
  2128. self._section("测谎瞄准(YOLO+ByteTrack)")
  2129. r = self._row()
  2130. self._check(r, "报警后自动瞄准", "aim_enabled", bool(aim.get("enabled", True)))
  2131. self._label(r, " 最长")
  2132. self._spin(r, "aim_duration", aim.get("duration_seconds", 25), 5, 120, 1, 4, "%.0f")
  2133. self._label(r, "秒")
  2134. r = self._row()
  2135. self._check(r, "测试按钮也开瞄准", "aim_on_manual",
  2136. bool(aim.get("on_manual_test", False)))
  2137. self._label(r, " 调试预览窗")
  2138. self._check(r, "开", "aim_overlay", bool(aim.get("show_overlay", False)))
  2139. # ---- 底部按钮
  2140. bar = tk.Frame(top, bg="#1f1f1f")
  2141. bar.pack(fill="x", padx=14, pady=(16, 12))
  2142. tk.Button(bar, text="恢复默认", width=8, command=self._restore,
  2143. font=self.font).pack(side="left")
  2144. tk.Button(bar, text="保存", width=8, command=self._save,
  2145. font=("Microsoft YaHei UI", 9, "bold")).pack(side="right")
  2146. tk.Button(bar, text="取消", width=8, command=self._close,
  2147. font=self.font).pack(side="right", padx=8)
  2148. top.update_idletasks()
  2149. w, h = top.winfo_width(), top.winfo_height()
  2150. sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
  2151. x = max(0, min(master.winfo_x() - w - 10, sw - w - 10))
  2152. if x < 10:
  2153. x = (sw - w) // 2
  2154. y = max(0, min(master.winfo_y(), sh - h - 40))
  2155. top.geometry("+%d+%d" % (x, y))
  2156. top.grab_set()
  2157. # ---- 搭界面用的小工具
  2158. def _section(self, text: str) -> None:
  2159. tk = self.tk
  2160. f = tk.Frame(self.top, bg="#1f1f1f")
  2161. f.pack(fill="x", padx=14, pady=(12, 2))
  2162. tk.Label(f, text=text, bg="#1f1f1f", fg="#f0c040",
  2163. font=("Microsoft YaHei UI", 10, "bold")).pack(anchor="w")
  2164. def _row(self):
  2165. tk = self.tk
  2166. f = tk.Frame(self.top, bg="#1f1f1f")
  2167. f.pack(fill="x", padx=14)
  2168. return f
  2169. def _check(self, parent, text: str, key: str, value: bool):
  2170. tk = self.tk
  2171. var = tk.BooleanVar(value=bool(value))
  2172. self.vars[key] = var
  2173. c = tk.Checkbutton(parent, text=text, variable=var, bg="#1f1f1f",
  2174. fg="#dddddd", selectcolor="#2a2a2a",
  2175. activebackground="#1f1f1f", activeforeground="#ffffff",
  2176. font=self.font, bd=0, highlightthickness=0)
  2177. c.pack(side="left")
  2178. return c
  2179. def _label(self, parent, text: str, pad=(8, 2)):
  2180. self.tk.Label(parent, text=text, bg="#1f1f1f", fg="#bbbbbb",
  2181. font=self.font).pack(side="left", padx=pad)
  2182. def _spin(self, parent, key: str, value, lo, hi, inc, width: int, fmt: str):
  2183. tk = self.tk
  2184. var = tk.StringVar(value=(fmt % value) if isinstance(value, (int, float))
  2185. else str(value))
  2186. self.vars[key] = var
  2187. s = tk.Spinbox(parent, from_=lo, to=hi, increment=inc, width=width,
  2188. textvariable=var, format=fmt, bg="#2a2a2a", fg="#ffffff",
  2189. insertbackground="#ffffff", buttonbackground="#3a3a3a",
  2190. relief="flat", font=self.font, justify="center",
  2191. highlightthickness=0)
  2192. s.pack(side="left")
  2193. return s
  2194. def _num(self, key: str, lo: float, hi: float, default: float,
  2195. as_int: bool = False):
  2196. try:
  2197. value = float(str(self.vars[key].get()).strip())
  2198. except Exception:
  2199. value = default
  2200. value = max(lo, min(hi, value))
  2201. return int(round(value)) if as_int else round(value, 2)
  2202. # ---- 按钮
  2203. def _restore(self) -> None:
  2204. d = DEFAULT_CONFIG
  2205. alert, hp, exp = d["alert"], d["hp_alert"], d["exp"]
  2206. values = {
  2207. "alert_sound": alert["sound"], "alert_sound_seconds": alert["sound_seconds"],
  2208. "alert_volume": alert["volume"], "alert_popup": alert["popup"],
  2209. "alert_popup_seconds": alert["popup_seconds"],
  2210. "bring_to_front": alert["bring_to_front"],
  2211. "save_snapshot": alert["save_snapshot"], "threshold": d["threshold"],
  2212. "min_hits": d["min_hits"], "max_fps": d["max_fps"],
  2213. "confirm_frames": d.get("confirm_frames", 2),
  2214. "require_layout": d.get("require_layout", True),
  2215. "auto_scale": True, "scale_value": 1.0,
  2216. "hp_enabled": hp["enabled"], "hp_low": hp["low_pct"],
  2217. "hp_recover": hp["recover_pct"], "mp_enabled": hp["mp_enabled"],
  2218. "mp_low": hp["mp_low_pct"], "mp_recover": hp["mp_recover_pct"],
  2219. "hp_repeat": hp["repeat_seconds"], "hp_sound": hp["sound"],
  2220. "hp_volume": hp["volume"], "exp_enabled": exp["enabled"],
  2221. "exp_window": exp["window"], "exp_sample": exp["sample_seconds"],
  2222. "aim_enabled": d.get("aim_assist", {}).get("enabled", True),
  2223. "aim_duration": d.get("aim_assist", {}).get("duration_seconds", 25),
  2224. "aim_on_manual": False, "aim_overlay": False,
  2225. }
  2226. for key, value in values.items():
  2227. var = self.vars.get(key)
  2228. if var is None:
  2229. continue
  2230. if isinstance(var, self.tk.BooleanVar):
  2231. var.set(bool(value))
  2232. else:
  2233. var.set(str(value) if isinstance(value, int) else "%.2f" % value)
  2234. log("设置已恢复成默认值(还没保存)")
  2235. def _save(self) -> None:
  2236. cfg = self.cfg
  2237. alert = cfg.setdefault("alert", {})
  2238. alert["sound"] = bool(self.vars["alert_sound"].get())
  2239. alert["sound_seconds"] = self._num("alert_sound_seconds", 3, 120, 10, True)
  2240. alert["volume"] = self._num("alert_volume", 0.1, 1.0, 0.9)
  2241. alert["popup"] = bool(self.vars["alert_popup"].get())
  2242. alert["popup_seconds"] = self._num("alert_popup_seconds", 3, 120, 12, True)
  2243. alert["bring_to_front"] = bool(self.vars["bring_to_front"].get())
  2244. alert["save_snapshot"] = bool(self.vars["save_snapshot"].get())
  2245. cfg["threshold"] = self._num("threshold", 0.5, 0.99, 0.75)
  2246. cfg["min_hits"] = self._num("min_hits", 1, 4, 2, True)
  2247. cfg["max_fps"] = self._num("max_fps", 1, 15, 5, True)
  2248. cfg["confirm_frames"] = self._num("confirm_frames", 1, 5, 2, True)
  2249. cfg["require_layout"] = bool(self.vars["require_layout"].get())
  2250. cfg["auto_scale"] = bool(self.vars["auto_scale"].get())
  2251. if not cfg["auto_scale"]:
  2252. # 取消自动适应 = 只按这个固定倍率查
  2253. cfg["scales"] = [self._num("scale_value", 0.5, 2.0, 1.0)]
  2254. hp = cfg.setdefault("hp_alert", {})
  2255. hp["enabled"] = bool(self.vars["hp_enabled"].get())
  2256. hp["low_pct"] = self._num("hp_low", 1, 95, 30, True)
  2257. hp["recover_pct"] = self._num("hp_recover", 1, 99, 35, True)
  2258. if hp["recover_pct"] <= hp["low_pct"]:
  2259. hp["recover_pct"] = min(99, hp["low_pct"] + 5)
  2260. hp["mp_enabled"] = bool(self.vars["mp_enabled"].get())
  2261. hp["mp_low_pct"] = self._num("mp_low", 1, 95, 10, True)
  2262. hp["mp_recover_pct"] = self._num("mp_recover", 1, 99, 15, True)
  2263. if hp["mp_recover_pct"] <= hp["mp_low_pct"]:
  2264. hp["mp_recover_pct"] = min(99, hp["mp_low_pct"] + 5)
  2265. hp["repeat_seconds"] = self._num("hp_repeat", 5, 300, 30, True)
  2266. hp["sound"] = bool(self.vars["hp_sound"].get())
  2267. hp["volume"] = self._num("hp_volume", 0.1, 1.0, 0.45)
  2268. exp = cfg.setdefault("exp", {})
  2269. exp["enabled"] = bool(self.vars["exp_enabled"].get())
  2270. exp["window"] = bool(self.vars["exp_window"].get())
  2271. exp["sample_seconds"] = self._num("exp_sample", 5, 120, 10, True)
  2272. aim = cfg.setdefault("aim_assist", {})
  2273. aim["enabled"] = bool(self.vars["aim_enabled"].get())
  2274. aim["duration_seconds"] = self._num("aim_duration", 5, 120, 25, True)
  2275. aim["on_manual_test"] = bool(self.vars["aim_on_manual"].get())
  2276. aim["show_overlay"] = bool(self.vars["aim_overlay"].get())
  2277. self.ctl.apply_config()
  2278. self._close()
  2279. def _close(self) -> None:
  2280. try:
  2281. self.top.grab_release()
  2282. except Exception:
  2283. pass
  2284. try:
  2285. self.top.destroy()
  2286. except Exception:
  2287. pass
  2288. if getattr(self.ctl, "app", None) is not None:
  2289. self.ctl.app.settings = None
  2290. # ---------------------------------------------------------------- 控制器
  2291. class Controller:
  2292. def __init__(self, cfg: dict, args):
  2293. self.cfg = cfg
  2294. self.args = args
  2295. self.app = None # StatusApp,设置页要用它找主窗口
  2296. self.events: "queue.Queue" = queue.Queue()
  2297. self.stats = Stats()
  2298. self.store = TemplateStore(TEMPLATE_DIR)
  2299. self.alerter = Alerter(cfg, popup_sink=self._sink,
  2300. quiet=bool(getattr(args, "silent", False)))
  2301. self.hud_alert = HudAlert(cfg, popup_sink=self._toast,
  2302. quiet=bool(getattr(args, "silent", False)))
  2303. self.aim = None
  2304. self.watcher = Watcher(cfg, self.store, self.alerter, self.stats,
  2305. region_override=getattr(args, "region", None),
  2306. hud_alert=self.hud_alert, aim=None)
  2307. self._init_aim()
  2308. def _init_aim(self) -> None:
  2309. """把 ch/ 里的 YOLO+ByteTrack + Interception 瞄准挂上来。"""
  2310. aim_cfg = dict(self.cfg.get("aim_assist") or {})
  2311. if not aim_cfg.get("enabled", True):
  2312. log("瞄准辅助:已关闭(config aim_assist.enabled=false)")
  2313. return
  2314. # exe:优先用解压目录里的 ch;源码:用项目旁的 ch/
  2315. candidates = []
  2316. if getattr(sys, "frozen", False):
  2317. candidates.append(BUNDLE_DIR / "ch")
  2318. candidates.append(APP_DIR / "ch")
  2319. ch_dir = next((p for p in candidates if p.is_dir()), None)
  2320. if ch_dir is None:
  2321. log("瞄准辅助:缺少 ch/ 目录,跳过")
  2322. return
  2323. # 权重:exe 旁可替换的一份优先,否则用包内
  2324. wcfg = aim_cfg.get("weights") or "models/best.pt"
  2325. wpath = Path(wcfg)
  2326. if not wpath.is_absolute():
  2327. for base in (APP_DIR / "ch", ch_dir):
  2328. cand = base / wcfg
  2329. if cand.exists():
  2330. wpath = cand
  2331. break
  2332. else:
  2333. wpath = ch_dir / wcfg
  2334. aim_cfg["weights"] = str(wpath)
  2335. try:
  2336. if str(ch_dir) not in sys.path:
  2337. sys.path.insert(0, str(ch_dir))
  2338. from tracker.aim_session import AimAssistController
  2339. self.aim = AimAssistController(
  2340. aim_cfg, region_fn=self.watcher.aim_region, log=log
  2341. )
  2342. self.watcher.aim = self.aim
  2343. log("瞄准辅助:就绪(%s · %s)" % (aim_cfg.get("backend", "bytetrack"), wpath.name))
  2344. except Exception as exc:
  2345. self.aim = None
  2346. log("瞄准辅助:加载失败(%s)" % exc)
  2347. def _sink(self, info: dict) -> None:
  2348. self.events.put(("alert", info))
  2349. def _toast(self, info: dict) -> None:
  2350. self.events.put(("toast", info))
  2351. def start(self) -> None:
  2352. self.watcher.start()
  2353. def apply_config(self) -> None:
  2354. """设置页点保存后:写回 config.json,并让能立刻生效的部分马上生效。"""
  2355. save_config(self.cfg)
  2356. # 音量是烧在 wav 里的,改了就重新合成
  2357. try:
  2358. self.alerter._wav = ensure_alarm_wav(
  2359. ASSET_DIR / "alarm.wav",
  2360. float(self.cfg.get("alert", {}).get("volume", 0.9)))
  2361. except Exception:
  2362. pass
  2363. try:
  2364. ha = self.cfg.get("hp_alert", {})
  2365. self.hud_alert._wav = (
  2366. ensure_hp_wav(ASSET_DIR / "hp_low.wav", float(ha.get("volume", 0.45)))
  2367. if ha.get("sound", True) else None)
  2368. except Exception:
  2369. pass
  2370. # 经验统计开关
  2371. want = bool(self.cfg.get("exp", {}).get("enabled"))
  2372. cur = getattr(self.watcher, "exp", None)
  2373. if want and cur is None:
  2374. self.watcher.exp = ExpTrack(self.cfg)
  2375. log("经验统计:已开启")
  2376. elif not want and cur is not None:
  2377. try:
  2378. cur.close()
  2379. except Exception:
  2380. pass
  2381. self.watcher.exp = None
  2382. log("经验统计:已关闭")
  2383. log("设置已保存,阈值 %.2f · 每秒 %d 次 · 连续 %d 帧 · 低血 %.0f%% · 瞄准 %s"
  2384. % (float(self.cfg.get("threshold", 0.75)),
  2385. int(self.cfg.get("max_fps", 5)),
  2386. int(self.cfg.get("confirm_frames", 2)),
  2387. float(self.cfg.get("hp_alert", {}).get("low_pct", 30)),
  2388. "开" if self.cfg.get("aim_assist", {}).get("enabled", True) else "关"))
  2389. # 缩放档位立刻生效
  2390. try:
  2391. self.watcher.apply_scale(self.cfg.get("scales") or [1.0],
  2392. bool(self.cfg.get("auto_scale", True)))
  2393. self.watcher.scale_from_hud = bool(self.cfg.get("scale_from_hud", True))
  2394. self.watcher._scale_probed = False
  2395. except Exception:
  2396. pass
  2397. # 瞄准开关:关→停;开→确保控制器在
  2398. try:
  2399. if self.cfg.get("aim_assist", {}).get("enabled", True):
  2400. if self.aim is None:
  2401. self._init_aim()
  2402. elif self.aim is not None:
  2403. self.aim.cfg = self.cfg.get("aim_assist") or {}
  2404. else:
  2405. if self.aim is not None:
  2406. self.aim.stop()
  2407. self.aim.cfg = self.cfg.get("aim_assist") or {}
  2408. except Exception:
  2409. pass
  2410. # 经验统计小窗跟着开关走
  2411. ecfg = self.cfg.get("exp", {})
  2412. win = getattr(self.app, "exp_win", None) if self.app is not None else None
  2413. if want and ecfg.get("window", True) and win is None and self.app is not None:
  2414. self.app.root.after(150, self.app._open_exp_window)
  2415. elif not want and win is not None:
  2416. try:
  2417. win.destroy()
  2418. except Exception:
  2419. pass
  2420. self.app.exp_win = None
  2421. def stop(self) -> None:
  2422. self.watcher.stop()
  2423. self.alerter.stop_sound()
  2424. if self.aim is not None:
  2425. try:
  2426. self.aim.stop()
  2427. except Exception:
  2428. pass
  2429. if getattr(self.watcher, "exp", None) is not None:
  2430. self.watcher.exp.close()
  2431. # ---------------------------------------------------------------- 各模式
  2432. def cmd_check(paths: List[str], cfg: dict, mark: bool = False) -> int:
  2433. store = TemplateStore(TEMPLATE_DIR)
  2434. if not store.items:
  2435. print("templates/ 里没有模板,先跑 learn 模式框一块")
  2436. return 2
  2437. matcher = build_matcher(cfg, store.items)
  2438. wide = None
  2439. wide_scales = list(cfg.get("scales_wide") or [])
  2440. threshold = float(cfg["threshold"])
  2441. min_hits = max(1, int(cfg.get("min_hits", 2)))
  2442. strong = float(cfg.get("strong_threshold", 0.92))
  2443. require_layout = bool(cfg.get("require_layout", True))
  2444. pair_avg = float(cfg.get("pair_avg_threshold", 0.82))
  2445. ok_all = True
  2446. for path in paths:
  2447. gray = imread_gray(path)
  2448. if gray is None:
  2449. print("读不到图片:%s" % path)
  2450. ok_all = False
  2451. continue
  2452. hit, per = matcher.match(gray, early_exit=False, full=True)
  2453. if hit.score < threshold and len(wide_scales) > 1:
  2454. # 常规档位没认出来,按常见缩放再扫一遍(诊断用,慢一点没关系)
  2455. if wide is None:
  2456. wide = build_matcher(cfg, store.items, wide_scales)
  2457. wh, wper = wide.match(gray, early_exit=False, full=True)
  2458. if wh.score > hit.score:
  2459. print("(按 x%.2f 认出来的,你的画面缩放和模板不一样)" % wh.scale)
  2460. hit, per = wh, wper
  2461. clustered = cluster_hits(per, threshold) if require_layout \
  2462. else _hit_items(per, threshold)
  2463. hits = sum(1 for _, v in clustered
  2464. if float(v.get("score", 0.0)) >= threshold)
  2465. print("\n== %s (%dx%d) ==" % (Path(path).name, gray.shape[1], gray.shape[0]))
  2466. for name, info in sorted(per.items(), key=lambda kv: -kv[1]["score"]):
  2467. print(" %-28s %.3f x%.2f 在 (%d,%d)"
  2468. % (name, info["score"], info["scale"],
  2469. info["rect"][0], info["rect"][1]))
  2470. ok = is_confirmed(hit, per, threshold, min_hits, strong,
  2471. require_layout=require_layout, pair_avg=pair_avg)
  2472. if not ok:
  2473. ok_all = False
  2474. print(" 最高 %.3f (%s x%.2f),簇内 %d 个过线 -> %s"
  2475. "(阈值 %.2f,至少 %d 个;双模板均分≥%.2f;强阈值 %.2f;布局校验 %s)"
  2476. % (hit.score, hit.name, hit.scale, hits,
  2477. "命中" if ok else "不命中", threshold, min_hits, pair_avg,
  2478. strong, "开" if require_layout else "关"))
  2479. if mark:
  2480. out = LOG_DIR / ("marked_%s" % Path(path).name)
  2481. LOG_DIR.mkdir(parents=True, exist_ok=True)
  2482. if imwrite(out, annotate(gray, per, threshold, winner=hit.name)):
  2483. print(" 已把匹配位置画出来:%s" % out)
  2484. return 0 if ok_all else 1
  2485. def cmd_once(cfg: dict, args) -> int:
  2486. store = TemplateStore(TEMPLATE_DIR)
  2487. matcher = build_matcher(cfg, store.items)
  2488. grabber = ScreenGrabber()
  2489. region = args.region
  2490. if region is None:
  2491. hwnd, rect = find_game_window(cfg["game_window_titles"])
  2492. region = rect or virtual_screen()
  2493. if hwnd:
  2494. print("游戏窗口 hwnd=0x%X 客户区=%s" % (hwnd, region))
  2495. region = clamp_region(region)
  2496. t0 = time.perf_counter()
  2497. gray = grabber.grab_gray(*region)
  2498. grab_ms = (time.perf_counter() - t0) * 1000
  2499. if gray is None:
  2500. print("抓屏失败")
  2501. return 2
  2502. # 走正式监控同一条路径,测出来的耗时才是真实值
  2503. t0 = time.perf_counter()
  2504. hit, per = matcher.match(gray)
  2505. match_ms = (time.perf_counter() - t0) * 1000
  2506. print("区域 %s 抓屏 %.1fms 识别 %.1fms" % (region, grab_ms, match_ms))
  2507. threshold = float(cfg["threshold"])
  2508. min_hits = max(1, int(cfg.get("min_hits", 2)))
  2509. strong = float(cfg.get("strong_threshold", 0.92))
  2510. require_layout = bool(cfg.get("require_layout", True))
  2511. pair_avg = float(cfg.get("pair_avg_threshold", 0.82))
  2512. clustered = cluster_hits(per, threshold) if require_layout \
  2513. else _hit_items(per, threshold)
  2514. hits = sum(1 for _, v in clustered
  2515. if float(v.get("score", 0.0)) >= threshold)
  2516. for name, info in sorted(per.items(), key=lambda kv: -kv[1]["score"]):
  2517. print(" %-28s %.3f x%.2f 在 (%d,%d)"
  2518. % (name, info["score"], info["scale"],
  2519. info["rect"][0], info["rect"][1]))
  2520. ok = is_confirmed(hit, per, threshold, min_hits, strong,
  2521. require_layout=require_layout, pair_avg=pair_avg)
  2522. print("粗查 %.3f → 最终 %.3f (%s%s) 簇内 %d 个过线 -> %s"
  2523. % (hit.coarse, hit.score, hit.name,
  2524. " 已复核" if hit.verified else "", hits, "命中" if ok else "不命中"))
  2525. grabber.close()
  2526. return 0 if ok else 1
  2527. def cmd_list() -> int:
  2528. print("屏幕上的顶层窗口(找游戏窗口标题用):")
  2529. for hwnd, title in iter_windows():
  2530. try:
  2531. _x, _y, w, h = client_rect(hwnd)
  2532. except Exception:
  2533. w = h = 0
  2534. print(" 0x%08X %4dx%-4d %s" % (hwnd, w, h, title))
  2535. return 0
  2536. def cmd_learn(cfg: dict, args) -> int:
  2537. delay = max(1, int(getattr(args, "delay", 3)))
  2538. print("把游戏画面切到「谎言探测仪」这个界面,别动。")
  2539. for i in range(delay, 0, -1):
  2540. print(" %d 秒后截屏…" % i, end="\r", flush=True)
  2541. time.sleep(1)
  2542. print(" " * 30, end="\r")
  2543. hwnd, rect = find_game_window(cfg["game_window_titles"])
  2544. region = args.region or rect or virtual_screen()
  2545. region = clamp_region(region)
  2546. grabber = ScreenGrabber()
  2547. img = grabber.grab_bgr(*region)
  2548. grabber.close()
  2549. if img is None or img.size == 0:
  2550. print("抓屏失败")
  2551. return 2
  2552. print("截到 %s。在弹出的窗口里,按住左键框一块「有字的地方」,回车确认,c 取消。"
  2553. % (region,))
  2554. win = "框选:框住测谎仪窗口里的一小段文字"
  2555. cv2.namedWindow(win, cv2.WINDOW_NORMAL)
  2556. max_w = 1400
  2557. if img.shape[1] > max_w:
  2558. s = max_w / float(img.shape[1])
  2559. cv2.resizeWindow(win, max_w, int(img.shape[0] * s))
  2560. else:
  2561. cv2.resizeWindow(win, img.shape[1], img.shape[0])
  2562. x, y, w, h = cv2.selectROI(win, img, showCrosshair=True, fromCenter=False)
  2563. cv2.destroyAllWindows()
  2564. if w < 12 or h < 8:
  2565. print("没框选或框得太小,已取消。")
  2566. return 1
  2567. crop = img[int(y):int(y) + int(h), int(x):int(x) + int(w)]
  2568. if float(crop.std()) < 6:
  2569. print("框到的画面几乎是纯色,认不出来。换一块有文字的地方再试。")
  2570. return 1
  2571. TEMPLATE_DIR.mkdir(parents=True, exist_ok=True)
  2572. out = TEMPLATE_DIR / ("learned_%s.png" % time.strftime("%Y%m%d_%H%M%S"))
  2573. if not imwrite(out, crop):
  2574. print("保存失败:%s" % out)
  2575. return 2
  2576. print("已保存模板:%s (%dx%d)" % (out.name, crop.shape[1], crop.shape[0]))
  2577. print("监控开着的话会自动加载,不用重启。")
  2578. return 0
  2579. def cmd_demo(cfg: dict, args) -> int:
  2580. import tkinter as tk
  2581. img_path = ASSET_DIR / "lie_detector_window.png"
  2582. if not img_path.exists():
  2583. print("缺少演示图:%s" % img_path)
  2584. return 2
  2585. root = tk.Tk()
  2586. root.withdraw()
  2587. photo = tk.PhotoImage(file=str(img_path))
  2588. w, h = photo.width(), photo.height()
  2589. gap = float(getattr(args, "gap", 8.0))
  2590. count = int(getattr(args, "count", 1))
  2591. show_seconds = float(getattr(args, "seconds", 12.0))
  2592. shown = 0
  2593. # 假窗口要出现在「程序监控的那块画面」里:有游戏就摆游戏客户区中间,没游戏就摆屏幕中间
  2594. _hwnd, _rect = find_game_window(cfg.get("game_window_titles", []))
  2595. def area():
  2596. if _rect and cfg.get("capture") != "screen":
  2597. return _rect
  2598. return (0, 0, root.winfo_screenwidth(), root.winfo_screenheight())
  2599. def show_one():
  2600. nonlocal shown
  2601. shown += 1
  2602. ax, ay, aw, ah = area()
  2603. top = tk.Toplevel(root)
  2604. top.overrideredirect(True)
  2605. top.attributes("-topmost", True)
  2606. top.geometry("%dx%d+%d+%d" % (w, h, ax + (aw - w) // 2, ay + (ah - h) // 2))
  2607. tk.Label(top, image=photo, borderwidth=0, highlightthickness=0).pack()
  2608. print("已弹出假的测谎窗口(第 %d/%d 次),%d 秒后自动关闭。"
  2609. % (shown, count, int(show_seconds)), flush=True)
  2610. def close():
  2611. try:
  2612. top.destroy()
  2613. except Exception:
  2614. pass
  2615. if shown < count:
  2616. root.after(int(gap * 1000), show_one)
  2617. else:
  2618. root.after(500, root.destroy)
  2619. top.after(int(show_seconds * 1000), close)
  2620. print("演示模式:%d 秒后弹出假窗口。监控程序应该会在 1 秒内报警。" % int(gap))
  2621. root.after(int(gap * 1000), show_one)
  2622. root.mainloop()
  2623. return 0
  2624. def cmd_hud(cfg: dict, args) -> int:
  2625. """读一次 HUD:对图片或对现在的游戏画面,看能不能认出血蓝经验。"""
  2626. reader = HudReader()
  2627. if not reader.ready:
  2628. print("templates/hud 里没有字形模板")
  2629. return 2
  2630. if args.paths:
  2631. path = args.paths[0]
  2632. gray = imread_gray(path)
  2633. if gray is None:
  2634. print("读不到图片:%s" % path)
  2635. return 2
  2636. print("图片:%s (%dx%d)" % (path, gray.shape[1], gray.shape[0]))
  2637. else:
  2638. hwnd, rect = find_game_window(cfg.get("game_window_titles", []))
  2639. if not hwnd:
  2640. print("没找到游戏窗口(最小化或没开)")
  2641. return 2
  2642. gray = ScreenGrabber().grab_gray(*rect)
  2643. if gray is None:
  2644. print("抓屏失败")
  2645. return 2
  2646. print("游戏窗口:%dx%d @ (%d,%d)" % (rect[2], rect[3], rect[0], rect[1]))
  2647. vals = reader.read(gray)
  2648. for key, label in (("hp", "血量"), ("mp", "蓝量"), ("exp", "经验")):
  2649. v = vals.get(key)
  2650. if v is None:
  2651. print(" %s:读不到" % label)
  2652. elif key == "exp":
  2653. total = (v[0] * 100.0 / v[1]) if v[1] > 0 else None
  2654. print(" %s:%d (%.2f%%) 这级共约 %s"
  2655. % (label, v[0], v[1], fmt_exp(total)))
  2656. else:
  2657. print(" %s:%d / %d (%.0f%%)"
  2658. % (label, v[0], v[1], v[0] * 100.0 / max(1, v[1])))
  2659. return 0 if any(vals.values()) else 1
  2660. def cmd_watch(cfg: dict, args) -> int:
  2661. ctl = Controller(cfg, args)
  2662. if not ctl.store.items:
  2663. print("templates/ 里没有模板。先放模板,或者跑 learn 模式框一块。")
  2664. return 2
  2665. if getattr(args, "no_gui", False):
  2666. ctl.start()
  2667. log("已启动(无界面)。Ctrl+C 退出。")
  2668. try:
  2669. while ctl.watcher.is_alive():
  2670. time.sleep(0.3)
  2671. except KeyboardInterrupt:
  2672. print("\n退出中…")
  2673. finally:
  2674. ctl.stop()
  2675. return 0
  2676. app = StatusApp(ctl)
  2677. ctl.app = app
  2678. ctl.start()
  2679. try:
  2680. app.run()
  2681. finally:
  2682. ctl.stop()
  2683. return 0
  2684. # ---------------------------------------------------------------- 入口
  2685. def load_config() -> dict:
  2686. cfg = json.loads(json.dumps(DEFAULT_CONFIG)) # 深拷贝
  2687. if CONFIG_PATH.exists():
  2688. try:
  2689. with open(CONFIG_PATH, "r", encoding="utf-8-sig") as fh:
  2690. user = json.load(fh)
  2691. for key, value in user.items():
  2692. if isinstance(value, dict) and isinstance(cfg.get(key), dict):
  2693. cfg[key].update(value) # 分段配置:用户改了哪项就覆盖哪项
  2694. else:
  2695. cfg[key] = value
  2696. except Exception as exc:
  2697. print("config.json 读不了(%s),先用默认配置。" % exc)
  2698. return cfg
  2699. def save_config(cfg: dict) -> None:
  2700. try:
  2701. with open(CONFIG_PATH, "w", encoding="utf-8") as fh:
  2702. json.dump(cfg, fh, ensure_ascii=False, indent=2)
  2703. except Exception:
  2704. pass
  2705. def parse_region(text: str) -> Tuple[int, int, int, int]:
  2706. parts = [p for p in re.split(r"[,\sx]+", text.strip()) if p]
  2707. if len(parts) != 4:
  2708. raise argparse.ArgumentTypeError("区域格式:x,y,w,h")
  2709. return tuple(int(round(float(p))) for p in parts) # type: ignore
  2710. def build_parser() -> argparse.ArgumentParser:
  2711. p = argparse.ArgumentParser(
  2712. description="冒险岛 谎言探测仪 提醒工具",
  2713. formatter_class=argparse.RawDescriptionHelpFormatter,
  2714. epilog="例子:\n"
  2715. " python lie_watcher.py\n"
  2716. " python lie_watcher.py check test.png\n"
  2717. " python lie_watcher.py --no-gui --threshold 0.72\n")
  2718. p.add_argument("mode", nargs="?", default="watch",
  2719. choices=["watch", "demo", "check", "once", "learn", "list",
  2720. "init", "hud"])
  2721. p.add_argument("paths", nargs="*", help="check 模式要检查的图片")
  2722. p.add_argument("--no-gui", action="store_true", help="不显示状态小窗")
  2723. p.add_argument("--silent", action="store_true", help="不出声、不弹窗(只记日志)")
  2724. p.add_argument("--no-sound", action="store_true", help="关掉警报音")
  2725. p.add_argument("--no-popup", action="store_true", help="关掉红色提醒窗")
  2726. p.add_argument("--no-focus", action="store_true", help="不要把游戏窗口切到最前")
  2727. p.add_argument("--threshold", type=float, help="相似度阈值 0~1")
  2728. p.add_argument("--fps", type=float, help="每秒检查次数")
  2729. p.add_argument("--region", type=parse_region, help="固定监控区域 x,y,w,h")
  2730. p.add_argument("--delay", type=int, default=3, help="learn 模式截屏前等待秒数")
  2731. p.add_argument("--gap", type=float, default=8.0, help="demo 模式弹出前等待秒数")
  2732. p.add_argument("--count", type=int, default=1, help="demo 模式弹几次")
  2733. p.add_argument("--seconds", type=float, default=12.0, help="demo 模式每次停留秒数")
  2734. p.add_argument("--mark", action="store_true",
  2735. help="check 模式:把匹配到的位置画在图上,存 logs\\marked_*.png")
  2736. return p
  2737. def main(argv=None) -> int:
  2738. attach_console()
  2739. setup_console()
  2740. enable_dpi_awareness()
  2741. seed_bundled_data()
  2742. args = build_parser().parse_args(argv)
  2743. cfg = load_config()
  2744. if args.threshold is not None:
  2745. cfg["threshold"] = float(args.threshold)
  2746. if args.fps is not None:
  2747. cfg["max_fps"] = float(args.fps)
  2748. if args.no_sound:
  2749. cfg["alert"]["sound"] = False
  2750. if args.no_popup:
  2751. cfg["alert"]["popup"] = False
  2752. if args.no_focus:
  2753. cfg["alert"]["bring_to_front"] = False
  2754. if args.silent:
  2755. cfg["alert"].update({"sound": False, "voice": False, "popup": False,
  2756. "bring_to_front": False})
  2757. global CONFIG
  2758. CONFIG = cfg
  2759. TEMPLATE_DIR.mkdir(parents=True, exist_ok=True)
  2760. ASSET_DIR.mkdir(parents=True, exist_ok=True)
  2761. LOG_DIR.mkdir(parents=True, exist_ok=True)
  2762. if not CONFIG_PATH.exists():
  2763. save_config(cfg)
  2764. print("已生成默认配置:%s" % CONFIG_PATH)
  2765. mode = args.mode
  2766. if mode == "check":
  2767. if not args.paths:
  2768. print("check 需要图片路径,例如:python lie_watcher.py check shot.png")
  2769. return 2
  2770. return cmd_check(args.paths, cfg, mark=args.mark)
  2771. if mode == "once":
  2772. return cmd_once(cfg, args)
  2773. if mode == "list":
  2774. return cmd_list()
  2775. if mode == "hud":
  2776. return cmd_hud(cfg, args)
  2777. if mode == "learn":
  2778. return cmd_learn(cfg, args)
  2779. if mode == "demo":
  2780. return cmd_demo(cfg, args)
  2781. if mode == "init":
  2782. print("配置已生成:%s" % CONFIG_PATH)
  2783. print("模板目录:%s" % TEMPLATE_DIR)
  2784. return 0
  2785. return cmd_watch(cfg, args)
  2786. if __name__ == "__main__":
  2787. try:
  2788. sys.exit(main())
  2789. except KeyboardInterrupt:
  2790. print("\n已退出")
  2791. sys.exit(0)