| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158 |
- # -*- coding: utf-8 -*-
- """
- 冒险岛 · 谎言探测仪 提醒工具
- ================================================
- 只做一件事:盯着游戏画面,一旦「谎言探测仪」对话框出现,
- 立刻响警报 + 弹红窗 + 把游戏窗口切到最前,把你叫回电脑前。
- 不读内存、不注入、不模拟鼠标键盘,只截屏看画面。
- 用法:
- python lie_watcher.py 开始监控(带状态小窗)
- python lie_watcher.py --no-gui 只要声音/弹窗,不显示状态窗
- python lie_watcher.py demo 屏幕上弹一个假的测谎窗口,测试用
- python lie_watcher.py check a.png 对图片跑识别,看分数、调阈值
- python lie_watcher.py once 对当前屏幕跑一次识别
- python lie_watcher.py learn 框选一小块存成模板(适配你的分辨率)
- python lie_watcher.py list 列出屏幕上的窗口标题(找游戏窗口名用)
- """
- import argparse
- import ctypes
- import json
- import os
- import queue
- import re
- import shutil
- import sys
- import threading
- import time
- import wave
- from ctypes import wintypes
- from pathlib import Path
- from typing import Dict, List, Optional, Tuple
- import cv2
- import numpy as np
- # ---------------------------------------------------------------- 路径
- def _app_dir() -> Path:
- """配置/模板/日志放哪儿。
- 源码运行时放脚本旁边;打包成 exe 后放 exe 旁边——
- 这样别人拿到 exe 也能直接改 config.json、能 learn 新模板。
- """
- if getattr(sys, "frozen", False):
- return Path(sys.executable).resolve().parent
- return Path(__file__).resolve().parent
- APP_DIR = _app_dir()
- # exe = onefile 时,打包进去的模板/演示图会被解到临时目录,这里记住它在哪
- BUNDLE_DIR = Path(getattr(sys, "_MEIPASS", APP_DIR))
- TEMPLATE_DIR = APP_DIR / "templates"
- HUD_DIR = TEMPLATE_DIR / "hud"
- ASSET_DIR = APP_DIR / "assets"
- LOG_DIR = APP_DIR / "logs"
- CONFIG_PATH = APP_DIR / "config.json"
- APP_NAME = "测谎仪提醒"
- # ---------------------------------------------------------------- 默认配置
- DEFAULT_CONFIG = {
- # 游戏窗口标题:包含其中任意一个就算(不区分大小写)
- "game_window_titles": ["冒险岛怀旧服", "冒险岛", "MapleStory"],
- # game_window = 只截游戏窗口那块的画面(快、干扰少);screen = 整屏
- "capture": "game_window",
- # 模板缩放档位。1.0 = 和模板原尺寸一致;1.25 = 你的画面比模板大 25%
- # 每多一档就多一份耗时,先只查 1.0;档位不对时程序会自己扫一遍宽范围再记住
- "scales": [1.0],
- # 自动适应:档位不对时自己扫下面这些,扫到就把结果写进 scales(下次直接按它查)
- "auto_scale": True,
- # 隔一段时间扫一遍这些档位,防止你的画面缩放跟模板差太多
- # 覆盖常见窗口/DPI:约 0.65x(小窗/高 DPI)到 1.50x(大分辨率放大)
- "scales_wide": [
- 1.0, 0.95, 1.05, 0.9, 1.1, 0.85, 1.15, 0.8, 1.2,
- 0.75, 1.25, 0.7, 1.35, 0.65, 1.5,
- ],
- # 多少帧做一次宽范围扫描(帧数越少越保险,代价是更费 CPU)
- "rescan_every": 40,
- # 用底部 HP 标签推算 UI 缩放(多分辨率时比盲扫更准、更快)
- "scale_from_hud": True,
- # 粗查时把画面缩小几倍跑(2 = 半分辨率,快 4 倍);1 = 不缩,最准但最慢
- "scale_down": 2.0,
- # 相似度阈值,超过就算出现。低了误报,高了漏报
- # 0.75:挡掉聊天区「有点像」的误报;真测谎窗通常 0.90+
- "threshold": 0.75,
- # 至少要几个不同模板同时过阈值才算真的出现(2 能挡掉只有标题像的误报)
- "min_hits": 2,
- # 单独一个模板高到这个分数也直接认(防止某天字变了、只剩一块认得出时漏报)
- # 仍要求附近还有第二块「像」的(见 layout),避免标题撞到聊天字
- "strong_threshold": 0.92,
- # 命中模板必须挤在测谎对话框那么大的一块区域里(聊天框散落匹配直接否掉)
- "require_layout": True,
- # 只有 2 个模板过线时,平均分还得够高才认(真对话框通常远高于此)
- "pair_avg_threshold": 0.82,
- # 连续几帧都确认才报警(1=立刻报;2=挡一帧噪声/闪一下的误报)
- "confirm_frames": 2,
- # 每秒最多检查几次(想省 CPU 就调小,3 就算很够用了)
- "max_fps": 5,
- # 对话框一直在时,每隔多少秒再叫一次
- "alert_repeat_seconds": 15,
- "alert": {
- "sound": True, # 警报音
- "sound_seconds": 10, # 每次响多久
- "volume": 0.9, # 0.1 ~ 1.0
- "voice": False, # 语音播报(要系统有中文语音,没有会自动跳过)
- "popup": True, # 屏幕上的红色提醒窗
- "popup_seconds": 12, # 红色提醒窗自动关闭时间
- "bring_to_front": True, # 把游戏窗口切到最前
- "save_snapshot": True, # 触发时存一张现场截图到 logs/(方便看误报)
- "snooze_seconds": 60, # 点掉提醒窗后,多少秒内不再吵
- },
- # ---- 画面底部那条 HP / MP / EXP(读它才能做低血提醒和经验统计)
- "hud": {
- "enabled": True, # 关掉就完全不读血蓝,只做测谎
- },
- # ---- 血量/蓝量过低提醒(比测谎轻,不会盖住测谎的红窗)
- "hp_alert": {
- "enabled": True, # 总开关
- "low_pct": 30, # 低于这个百分比就提醒
- "recover_pct": 35, # 回到这个百分比以上才算脱险,下次掉下来才会再提醒
- "repeat_seconds": 30, # 一直低着不动,隔这么多秒再叫一次
- "mp_enabled": True, # 蓝量也提醒
- "mp_low_pct": 10, # 蓝量低于这个百分比提醒
- "mp_recover_pct": 15,
- "sound": True, # 短促两声,不是测谎那种连响
- "volume": 0.45,
- "popup": True, # 右上角小提示条
- "popup_seconds": 6,
- },
- # ---- 经验统计
- "exp": {
- "enabled": False, # 打开后会记录经验、算 1H 速率、画走势
- "sample_seconds": 10, # 每多少秒记一次
- "window_minutes": 5, # 「实时 1H」用最近多少分钟的样本算
- "save_csv": True, # 存 logs/exp_日期.csv,可以用 Excel 打开
- "window": True, # 打开经验统计小窗
- },
- # 状态小窗是否总在最前
- "status_on_top": False,
- # ---- 测谎出现后:YOLO+ByteTrack 跟踪 + Interception 鼠标跟红准星
- "aim_assist": {
- "enabled": True, # 报警后自动开瞄准
- "backend": "bytetrack", # bytetrack | deepsort
- "weights": "models/best.pt", # 相对 ch/ 目录
- "conf": 0.25,
- "imgsz": 640,
- "duration_seconds": 25, # 一次最长跟多久
- "miss_stop_frames": 45, # 连续丢目标这么多帧就停
- "gain": 1.0, # 跟手增益,1=尽量贴准星
- "deadzone": 1.5, # 像素死区,小于此不挪
- "min_conf": 0.20, # 低于此置信度当丢目标
- "show_overlay": False, # 调试预览窗(会抢焦点,挂机别开)
- "on_manual_test": False, # 点「测试」要不要也开瞄准
- },
- }
- # ---------------------------------------------------------------- 小工具
- def setup_console() -> None:
- """让中文在 cmd / PowerShell 里正常显示。"""
- try:
- ctypes.windll.kernel32.SetConsoleOutputCP(65001)
- except Exception:
- pass
- for stream in (sys.stdout, sys.stderr):
- try:
- if stream is not None:
- stream.reconfigure(encoding="utf-8", errors="replace")
- except Exception:
- pass
- def attach_console() -> None:
- """打包成无控制台的 exe 后:从 cmd / PowerShell 启动就借它的控制台打印,
- 双击启动没有控制台,那就安静跑(消息还是会写进 logs\\lie_watcher.log)。"""
- if sys.stdout is not None:
- return
- try:
- if not ctypes.windll.kernel32.AttachConsole(-1): # ATTACH_PARENT_PROCESS
- return
- sys.stdout = open("CONOUT$", "w", encoding="utf-8", errors="replace")
- sys.stderr = open("CONOUT$", "w", encoding="utf-8", errors="replace")
- except Exception:
- pass
- def seed_bundled_data() -> None:
- """exe 第一次运行时,把打包进去的模板/演示图/YOLO 权重复制到 exe 旁边。
- 之后所有东西都在 exe 旁边:config.json 能改、learn 出的新模板存得下、
- 报警截图写在 logs\\ 里,整个文件夹拷给别人也是一份完整可用的。
- ch/models 也会放出一份,方便以后只换权重不用重打包。
- """
- if not getattr(sys, "frozen", False):
- return
- for sub in ("templates", "assets", "ch/models", "第三方"):
- src = BUNDLE_DIR / sub
- if not src.exists():
- continue
- try:
- if src.is_file():
- target = APP_DIR / sub
- if not target.exists():
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(str(src), str(target))
- continue
- for item in src.rglob("*"): # 连 templates\hud\ 这种子目录一起
- target = APP_DIR / sub / item.relative_to(src)
- if item.is_dir():
- target.mkdir(parents=True, exist_ok=True)
- elif not target.exists():
- target.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(str(item), str(target))
- except OSError:
- pass
- def enable_dpi_awareness() -> None:
- """不声明 DPI 感知的话,1920x1080 在 125% 缩放下会被系统骗成 1536x864,坐标全错。"""
- try:
- ctypes.windll.shcore.SetProcessDpiAwareness(2) # 每显示器 v2
- return
- except Exception:
- pass
- try:
- ctypes.windll.user32.SetProcessDPIAware()
- except Exception:
- pass
- _log_lock = threading.Lock()
- def log(msg: str) -> None:
- line = "[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg)
- with _log_lock:
- try:
- if sys.stdout is not None:
- print(line, flush=True)
- except Exception:
- pass
- try:
- LOG_DIR.mkdir(parents=True, exist_ok=True)
- path = LOG_DIR / "lie_watcher.log"
- if path.exists() and path.stat().st_size > 2 * 1024 * 1024:
- path.replace(LOG_DIR / "lie_watcher.old.log")
- with open(path, "a", encoding="utf-8") as fh:
- fh.write(line + "\n")
- except Exception:
- pass
- def imread_gray(path) -> Optional[np.ndarray]:
- """读图。cv2.imread 不支持中文路径,所以走 imdecode。"""
- try:
- buf = np.fromfile(str(path), dtype=np.uint8)
- if buf.size == 0:
- return None
- return cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
- except Exception:
- return None
- def imwrite(path, img) -> bool:
- """存图。同样为了中文路径。"""
- try:
- ok, buf = cv2.imencode(".png", img)
- if not ok:
- return False
- buf.tofile(str(path))
- return True
- except Exception:
- return False
- # ---------------------------------------------------------------- GDI 抓屏
- SRCCOPY = 0x00CC0020
- CAPTUREBLT = 0x40000000
- user32 = ctypes.windll.user32
- gdi32 = ctypes.windll.gdi32
- class BITMAPINFOHEADER(ctypes.Structure):
- _fields_ = [
- ("biSize", wintypes.DWORD), ("biWidth", wintypes.LONG),
- ("biHeight", wintypes.LONG), ("biPlanes", wintypes.WORD),
- ("biBitCount", wintypes.WORD), ("biCompression", wintypes.DWORD),
- ("biSizeImage", wintypes.DWORD), ("biXPelsPerMeter", wintypes.LONG),
- ("biYPelsPerMeter", wintypes.LONG), ("biClrUsed", wintypes.DWORD),
- ("biClrImportant", wintypes.DWORD),
- ]
- class BITMAPINFO(ctypes.Structure):
- _fields_ = [("bmiHeader", BITMAPINFOHEADER), ("bmiColors", wintypes.DWORD * 3)]
- class ScreenGrabber:
- """ctypes 直接调 GDI 抓屏,不依赖 mss / Pillow。
- 复用同一个内存 DC 和缓冲区,1920x1080 一帧约 35~55ms。
- """
- def __init__(self):
- self._w = 0
- self._h = 0
- self._hdc = None
- self._mdc = None
- self._bmp = None
- self._buf = None
- self._bi = None
- def _release(self) -> None:
- try:
- if self._mdc and self._bmp:
- gdi32.SelectObject(self._mdc, self._bmp)
- if self._bmp:
- gdi32.DeleteObject(self._bmp)
- if self._mdc:
- gdi32.DeleteDC(self._mdc)
- if self._hdc:
- user32.ReleaseDC(None, self._hdc)
- except Exception:
- pass
- self._hdc = self._mdc = self._bmp = self._buf = self._bi = None
- self._w = self._h = 0
- def _prepare(self, w: int, h: int) -> None:
- self._release()
- self._hdc = user32.GetDC(None)
- self._mdc = gdi32.CreateCompatibleDC(self._hdc)
- self._bmp = gdi32.CreateCompatibleBitmap(self._hdc, w, h)
- gdi32.SelectObject(self._mdc, self._bmp)
- self._buf = ctypes.create_string_buffer(w * h * 4)
- bi = BITMAPINFO()
- bi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
- bi.bmiHeader.biWidth = w
- bi.bmiHeader.biHeight = -h # 负高度 = 自上而下
- bi.bmiHeader.biPlanes = 1
- bi.bmiHeader.biBitCount = 32
- bi.bmiHeader.biCompression = 0 # BI_RGB
- self._bi = bi
- self._w, self._h = w, h
- def grab_gray(self, x: int, y: int, w: int, h: int) -> Optional[np.ndarray]:
- w, h = max(1, int(w)), max(1, int(h))
- if (w, h) != (self._w, self._h):
- self._prepare(w, h)
- try:
- gdi32.BitBlt(self._mdc, 0, 0, w, h, self._hdc, int(x), int(y),
- SRCCOPY | CAPTUREBLT)
- gdi32.GetDIBits(self._mdc, self._bmp, 0, h, self._buf,
- ctypes.byref(self._bi), 0)
- arr = np.frombuffer(self._buf, dtype=np.uint8, count=w * h * 4)
- arr = arr.reshape(h, w, 4)
- return cv2.cvtColor(arr, cv2.COLOR_BGRA2GRAY)
- except Exception:
- return None
- def grab_bgr(self, x: int, y: int, w: int, h: int) -> Optional[np.ndarray]:
- gray = self.grab_gray(x, y, w, h)
- if gray is None:
- return None
- return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
- def close(self) -> None:
- self._release()
- # ---------------------------------------------------------------- 窗口
- def virtual_screen() -> Tuple[int, int, int, int]:
- return (user32.GetSystemMetrics(76), user32.GetSystemMetrics(77),
- user32.GetSystemMetrics(78), user32.GetSystemMetrics(79))
- def clamp_region(region: Tuple[int, int, int, int]) -> Tuple[int, int, int, int]:
- x, y, w, h = region
- vx, vy, vw, vh = virtual_screen()
- x2, y2 = min(x + w, vx + vw), min(y + h, vy + vh)
- x, y = max(x, vx), max(y, vy)
- return (int(x), int(y), int(max(1, x2 - x)), int(max(1, y2 - y)))
- def iter_windows() -> List[Tuple[int, str]]:
- found: List[Tuple[int, str]] = []
- proto = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
- def _cb(hwnd, _lparam):
- try:
- if user32.IsWindowVisible(hwnd):
- n = user32.GetWindowTextLengthW(hwnd)
- if n > 0:
- buf = ctypes.create_unicode_buffer(n + 1)
- user32.GetWindowTextW(hwnd, buf, n + 1)
- found.append((hwnd, buf.value))
- except Exception:
- pass
- return True
- user32.EnumWindows(proto(_cb), 0)
- return found
- def client_rect(hwnd: int) -> Tuple[int, int, int, int]:
- pt = wintypes.POINT(0, 0)
- user32.ClientToScreen(hwnd, ctypes.byref(pt))
- rc = wintypes.RECT()
- user32.GetClientRect(hwnd, ctypes.byref(rc))
- return (pt.x, pt.y, rc.right - rc.left, rc.bottom - rc.top)
- def find_game_window(titles: List[str]) -> Tuple[int, Optional[Tuple[int, int, int, int]]]:
- """按标题找游戏窗口,返回 (hwnd, 客户区屏幕矩形)。找不到返回 (0, None)。
- 优先级:标题完全一样 > 标题以它开头(越短越像)> 标题里包含它。
- 这一步很要紧:浏览器标签、聊天窗口的标题里也常有"冒险岛"
- (比如本工具的聊天窗口叫"冒险岛测谎界面提醒工具"),
- 只按"包含"来找会抓错窗口;只有一档"包含"命中时干脆不认,退回整屏监控。
- """
- keys = [k.strip().lower() for k in titles if k and k.strip()]
- best = None # (score, -len(title), area, hwnd, rect)
- for hwnd, title in iter_windows():
- if not title:
- continue
- low = title.strip().lower()
- score = 0
- for k in keys:
- if low == k:
- score = max(score, 3)
- elif low.startswith(k) and len(low) <= len(k) + 10:
- # 后面只能带一点点后缀(版本号、角色名之类);
- # "冒险岛测谎界面提醒工具 — 聊天窗口" 这种就不算了
- score = max(score, 2)
- elif k in low:
- score = max(score, 1)
- if not score:
- continue
- try:
- if user32.IsIconic(hwnd):
- continue
- except Exception:
- pass
- x, y, w, h = client_rect(hwnd)
- if w < 320 or h < 240:
- continue
- area = w * h
- rank = (score, -len(title.strip()), area)
- if best is None or rank > best[0]:
- best = (rank, hwnd, (x, y, w, h))
- if best is None or best[0][0] < 2:
- return 0, None
- return best[1], best[2]
- def game_window_minimized(titles: List[str]) -> bool:
- """游戏窗口在、但是被最小化了(最小化时截不到画面,只能待机)。"""
- keys = [k.strip().lower() for k in titles if k and k.strip()]
- for hwnd, title in iter_windows():
- if not title:
- continue
- low = title.strip().lower()
- if not any(low == k or (low.startswith(k) and len(low) <= len(k) + 10)
- or k in low for k in keys):
- continue
- try:
- if user32.IsIconic(hwnd):
- return True
- except Exception:
- pass
- return False
- def force_foreground(hwnd: int) -> bool:
- """把窗口拉到最前。Windows 会拦后台程序抢焦点,按一下 Alt 解锁再抢。"""
- if not hwnd:
- return False
- try:
- if user32.IsIconic(hwnd):
- user32.ShowWindow(hwnd, 9) # SW_RESTORE
- user32.keybd_event(0x12, 0, 0, 0) # Alt down
- user32.keybd_event(0x12, 0, 2, 0) # Alt up
- user32.SetForegroundWindow(hwnd)
- user32.BringWindowToTop(hwnd)
- return True
- except Exception:
- return False
- def flash_window(hwnd: int) -> None:
- """任务栏图标闪。"""
- class FLASHWINFO(ctypes.Structure):
- _fields_ = [("cbSize", wintypes.UINT), ("hwnd", wintypes.HWND),
- ("dwFlags", wintypes.DWORD), ("uCount", wintypes.UINT),
- ("dwTimeout", wintypes.DWORD)]
- try:
- info = FLASHWINFO(ctypes.sizeof(FLASHWINFO), hwnd, 0x00000003, 8, 0)
- user32.FlashWindowEx(ctypes.byref(info))
- except Exception:
- pass
- # ---------------------------------------------------------------- 模板与匹配
- class Template:
- __slots__ = ("name", "gray", "_cache")
- def __init__(self, name: str, gray: np.ndarray):
- self.name = name
- self.gray = gray
- self._cache: Dict[float, np.ndarray] = {}
- def scaled(self, scale: float) -> np.ndarray:
- key = round(scale, 3)
- hit = self._cache.get(key)
- if hit is not None:
- return hit
- h, w = self.gray.shape[:2]
- nh = max(4, int(round(h * scale)))
- nw = max(4, int(round(w * scale)))
- interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_LINEAR
- img = cv2.resize(self.gray, (nw, nh), interpolation=interp)
- self._cache[key] = img
- return img
- class TemplateStore:
- """templates/ 目录里的所有 png。支持运行中新增(learn 模式)自动生效。"""
- def __init__(self, directory: Path):
- self.dir = directory
- self.items: List[Template] = []
- self._sig = None
- self.reload()
- def _signature(self):
- try:
- return tuple(sorted((p.name, p.stat().st_mtime_ns)
- for p in self.dir.glob("*.png")))
- except Exception:
- return ()
- def reload(self) -> List[Template]:
- items: List[Template] = []
- try:
- for path in sorted(self.dir.glob("*.png")):
- img = imread_gray(path)
- if img is None or min(img.shape[:2]) < 10:
- continue
- items.append(Template(path.stem, img))
- except Exception:
- pass
- items.sort(key=lambda t: t.gray.size) # 小的先试,便宜
- self.items = items
- self._sig = self._signature()
- return items
- def maybe_reload(self) -> bool:
- if self._signature() != self._sig:
- self.reload()
- return True
- return False
- class MatchHit:
- __slots__ = ("score", "coarse", "name", "scale", "rect", "verified")
- def __init__(self, score: float = 0.0, coarse: float = 0.0, name: str = "",
- scale: float = 1.0, rect: Tuple[int, int, int, int] = (0, 0, 0, 0),
- verified: bool = False):
- self.score = score # 最终分数(复核过就是全分辨率分数)
- self.coarse = coarse # 粗查分数
- self.name = name
- self.scale = scale
- self.rect = rect
- self.verified = verified
- def __repr__(self) -> str:
- return "MatchHit(%.3f, %s, x%.2f, %s)" % (self.score, self.name,
- self.scale, self.rect)
- class Matcher:
- """多尺度模板匹配。
- 全分辨率跑一遍要命(1000x750 一张 55ms,20 个组合就是 1 秒多),
- 所以:先把画面缩小 scale_down 倍做粗查,粗查可疑时再用全分辨率复核。
- 粗查负责"快",复核负责"准"。
- """
- def __init__(self, templates: List[Template], scales: List[float],
- threshold: float, scale_down: float = 2.0):
- # 大模板信息量大,先试它,一次命中就能早退
- self.templates = sorted(templates, key=lambda t: -int(t.gray.size))
- self.scales = list(scales)
- self.threshold = float(threshold)
- self.scale_down = max(1.0, float(scale_down))
- # 粗查多少分以上才值得花大价钱做全分辨率复核。
- # 实测:纯背景 0.57,但游戏画面里到处是小字,半分辨率下噪声能到 0.67;
- # 真对话框粗查是 0.85+,所以门槛放在 0.70 既不会白忙也不漏
- self.coarse_threshold = max(0.70, self.threshold)
- def _template(self, name: str) -> Optional[Template]:
- for tpl in self.templates:
- if tpl.name == name:
- return tpl
- return None
- def _scan(self, gray: np.ndarray, eff_scales: List[float], ds: float,
- early_exit: bool, stop_at: float):
- H, W = gray.shape[:2]
- best = MatchHit()
- per: Dict[str, dict] = {}
- for tpl in self.templates:
- s_best, s_scale, s_loc, s_size = -1.0, 1.0, None, (0, 0)
- for eff in eff_scales:
- tm = tpl.scaled(eff)
- th, tw = tm.shape[:2]
- if tw > W or th > H or tw < 10 or th < 6:
- continue
- try:
- res = cv2.matchTemplate(gray, tm, cv2.TM_CCOEFF_NORMED)
- except cv2.error:
- continue
- res = np.nan_to_num(res, nan=0.0, posinf=0.0, neginf=0.0)
- _, mx, _, loc = cv2.minMaxLoc(res)
- if mx > s_best:
- s_best, s_scale, s_loc, s_size = float(mx), eff, loc, (tw, th)
- if early_exit and s_best >= stop_at:
- break
- if s_loc is None:
- continue
- rect = (int(s_loc[0] * ds), int(s_loc[1] * ds),
- int(s_size[0] * ds), int(s_size[1] * ds))
- per[tpl.name] = {"score": s_best, "scale": s_scale * ds, "rect": rect}
- if s_best > best.coarse:
- best = MatchHit(score=s_best, coarse=s_best, name=tpl.name,
- scale=s_scale * ds, rect=rect)
- return best, per
- def match(self, gray: np.ndarray, early_exit: bool = True, full: bool = False):
- """返回 (最佳 MatchHit, {模板名: {score, scale, rect}})。
- per 里带位置,方便把"到底匹配到哪块"画出来查误报。
- full=True 时全分辨率、全档位、不早退 —— 给 check/once 调参用,慢但最准。
- """
- ds = 1.0
- work = gray
- if not full and self.scale_down > 1.01:
- ds = self.scale_down
- # 大画面再多缩一点,不然全屏 1920x1080 会把一个核吃满
- px = gray.shape[0] * gray.shape[1]
- if px > 1.4e6:
- ds = max(ds, 3.0)
- nw = max(32, int(round(gray.shape[1] / ds)))
- nh = max(32, int(round(gray.shape[0] / ds)))
- work = cv2.resize(gray, (nw, nh), interpolation=cv2.INTER_AREA)
- eff = [s / ds for s in self.scales] if ds > 1.0 else list(self.scales)
- stop_at = self.threshold if full else max(0.85, self.threshold)
- hit, per = self._scan(work, eff, ds, early_exit and not full, stop_at)
- if full or hit.coarse < self.coarse_threshold:
- return hit, per
- # 粗查可疑 → 全分辨率复核,确认了才算数(宁可漏一顿,不要误报)
- tpl = self._template(hit.name)
- if tpl is None:
- return hit, per
- best_score = hit.coarse
- best_scale = hit.scale
- best_rect = hit.rect
- # 先按粗查给出的那个档位复核;过了就收工,没过再试相邻的 ±2.5%
- for sv in (hit.scale, hit.scale * 0.975, hit.scale * 1.025):
- tm = tpl.scaled(sv)
- if tm.shape[0] > gray.shape[0] or tm.shape[1] > gray.shape[1]:
- continue
- try:
- res = cv2.matchTemplate(gray, tm, cv2.TM_CCOEFF_NORMED)
- except cv2.error:
- continue
- res = np.nan_to_num(res, nan=0.0, posinf=0.0, neginf=0.0)
- _, mx, _, loc = cv2.minMaxLoc(res)
- if mx > best_score:
- best_score = float(mx)
- best_scale = sv
- best_rect = (int(loc[0]), int(loc[1]),
- int(tm.shape[1]), int(tm.shape[0]))
- if best_score >= self.threshold:
- break
- per[hit.name] = {"score": best_score, "scale": best_scale,
- "rect": best_rect}
- return MatchHit(best_score, hit.coarse, hit.name, best_scale, best_rect,
- verified=True), per
- def count_hits(per: Dict[str, dict], threshold: float) -> int:
- """这一帧里有多少个模板过了阈值。"""
- return sum(1 for v in per.values() if float(v.get("score", 0.0)) >= threshold)
- def _hit_items(per: Dict[str, dict], threshold: float):
- """过阈值的 (名字, info),按分数从高到低。"""
- items = [(n, v) for n, v in per.items()
- if float(v.get("score", 0.0)) >= threshold]
- items.sort(key=lambda kv: -float(kv[1].get("score", 0.0)))
- return items
- def cluster_hits(per: Dict[str, dict], threshold: float,
- soft: float = 0.0) -> List[Tuple[str, dict]]:
- """把过线(或接近过线)的模板收成「同一块对话框」里的一组。
- 真测谎窗:标题/倒计时/说明/规则挤在约 370×220(×缩放)的白窗里,缩放一致。
- 误报常见:聊天区两处各撞上一个模板,中心相距很远或缩放对不上。
- """
- hard = _hit_items(per, threshold)
- soft_thr = max(0.45, float(soft) if soft > 0 else threshold - 0.12)
- pool = _hit_items(per, soft_thr)
- if not pool:
- return []
- def _center(info: dict):
- x, y, w, h = info.get("rect", (0, 0, 0, 0))
- return (x + w * 0.5, y + h * 0.5)
- def _scale(info: dict) -> float:
- return max(0.2, float(info.get("scale", 1.0)))
- # 以最高分为锚点,吸入缩放接近、距离在对话框范围内的其它块
- anchor_name, anchor = pool[0]
- as_ = _scale(anchor)
- ax, ay = _center(anchor)
- max_dx = 420.0 * as_
- max_dy = 280.0 * as_
- clustered = [(anchor_name, anchor)]
- for name, info in pool[1:]:
- if abs(_scale(info) / as_ - 1.0) > 0.10:
- continue
- cx, cy = _center(info)
- if abs(cx - ax) <= max_dx and abs(cy - ay) <= max_dy:
- clustered.append((name, info))
- # 整簇外接矩形也不能大得离谱(挡住「锚点附近刚好各有一块」但其实横跨半屏)
- if len(clustered) >= 2:
- left = min(v["rect"][0] for _, v in clustered)
- right = max(v["rect"][0] + v["rect"][2] for _, v in clustered)
- top = min(v["rect"][1] for _, v in clustered)
- bot = max(v["rect"][1] + v["rect"][3] for _, v in clustered)
- if (right - left) > 560.0 * as_ or (bot - top) > 380.0 * as_:
- # 退回:只留硬过线且彼此仍近的
- clustered = [(n, v) for n, v in clustered
- if float(v.get("score", 0.0)) >= threshold]
- if len(clustered) >= 2:
- left = min(v["rect"][0] for _, v in clustered)
- right = max(v["rect"][0] + v["rect"][2] for _, v in clustered)
- top = min(v["rect"][1] for _, v in clustered)
- bot = max(v["rect"][1] + v["rect"][3] for _, v in clustered)
- if (right - left) > 560.0 * as_ or (bot - top) > 380.0 * as_:
- return hard[:1]
- # 有标题时,标题应在其它块上方(测谎窗标题贴顶)
- by_name = {n: v for n, v in clustered}
- title = None
- for key in by_name:
- if key == "01_title" or key.endswith("_title") or "title" in key.lower():
- title = by_name[key]
- break
- if title is not None and len(clustered) >= 2:
- ty = title["rect"][1] + title["rect"][3] * 0.5
- others_y = [v["rect"][1] + v["rect"][3] * 0.5
- for n, v in clustered if v is not title]
- if others_y and ty > min(others_y) + 30 * as_:
- return [(n, v) for n, v in clustered if v is not title][:1] or hard[:1]
- return clustered
- def is_confirmed(hit, per: Dict[str, dict], threshold: float, min_hits: int,
- strong: float, require_layout: bool = True,
- pair_avg: float = 0.82) -> bool:
- """要不要认定「测谎仪出现了」。
- 比「过线个数」多两道闸:
- 1) 命中块必须挤在对话框大小的区域里(require_layout)
- 2) 只有 2 个模板过线时,平均分还要够高(挡聊天区擦边球)
- 超高分单模板仍可认,但附近还得有第二块「像」的,避免标题撞字。
- """
- if hit is None or hit.score < min(threshold, strong):
- # 连 soft 都不够,直接否
- if hit is None or hit.score < threshold * 0.85:
- return False
- clustered = cluster_hits(per, threshold) if require_layout else _hit_items(per, threshold)
- hard = [(n, v) for n, v in clustered
- if float(v.get("score", 0.0)) >= threshold]
- hits = len(hard)
- best = float(hard[0][1]["score"]) if hard else float(hit.score)
- if hits >= max(3, min_hits + 1):
- return best >= threshold
- if hits >= min_hits:
- avg = sum(float(v["score"]) for _, v in hard) / float(hits)
- # 两个擦边(0.70/0.72)平均只有 0.71,过不了 pair_avg;真窗通常 0.9+
- if hits == 2 and avg < float(pair_avg):
- return False
- return best >= threshold
- # 强命中兜底:主分很高,且同簇里还有第二块接近阈值的
- if best >= strong or hit.score >= strong:
- soft = cluster_hits(per, threshold, soft=threshold - 0.10) if require_layout \
- else _hit_items(per, threshold - 0.10)
- near = len(soft)
- if near >= 2 and (best >= strong or hit.score >= strong):
- return True
- # 极高分且已全分辨率复核过,才允许单模板(几乎不可能是巧合)
- if hit.verified and hit.score >= max(strong, 0.96):
- return True
- return False
- def estimate_ui_scale(gray: np.ndarray, hud_labels: Dict[str, np.ndarray],
- candidates: Optional[List[float]] = None) -> Optional[float]:
- """用底部 HP/MP/EXP 标签推算当前 UI 相对模板的缩放。
- 标签几乎每帧都在,比盲扫测谎模板更稳;分辨率/DPI 变了这里最先反映出来。
- """
- if gray is None or gray.shape[0] < 80 or not hud_labels:
- return None
- scales = candidates or [
- 1.0, 0.95, 1.05, 0.9, 1.1, 0.85, 1.15, 0.8, 1.2,
- 0.75, 1.25, 0.7, 1.35, 0.65, 1.5,
- ]
- y0 = max(0, gray.shape[0] - max(80, int(gray.shape[0] * 0.12)))
- strip = gray[y0:]
- best_s, best_sc = 1.0, -1.0
- # 优先用 HP,没有就试 MP/EXP
- order = [k for k in ("hp", "mp", "exp") if k in hud_labels]
- if not order:
- return None
- for key in order:
- tpl = hud_labels[key]
- th0, tw0 = tpl.shape[:2]
- for s in scales:
- nh = max(4, int(round(th0 * s)))
- nw = max(4, int(round(tw0 * s)))
- if nh >= strip.shape[0] or nw >= strip.shape[1]:
- continue
- interp = cv2.INTER_AREA if s < 1.0 else cv2.INTER_LINEAR
- tm = cv2.resize(tpl, (nw, nh), interpolation=interp)
- try:
- res = cv2.matchTemplate(strip, tm, cv2.TM_CCOEFF_NORMED)
- except cv2.error:
- continue
- res = np.nan_to_num(res, nan=0.0, posinf=0.0, neginf=0.0)
- sc = float(cv2.minMaxLoc(res)[1])
- if sc > best_sc:
- best_sc, best_s = sc, float(s)
- if best_sc >= 0.70:
- return round(best_s, 3)
- return round(best_s, 3) if best_sc >= 0.55 else None
- def annotate(gray: np.ndarray, per: Dict[str, dict], threshold: float,
- winner: str = ""):
- """把每个模板匹配到的位置画到图上:绿框=过了阈值,橙框=有几分像但没过。
- 存现场截图时用,误报了能一眼看出它是拿哪块画面当的测谎仪。
- """
- img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
- h, w = img.shape[:2]
- for name, info in sorted(per.items(), key=lambda kv: -float(kv[1].get("score", 0.0))):
- sc = float(info.get("score", 0.0))
- if sc < max(0.50, threshold - 0.25):
- continue
- bx, by, bw, bh = [int(v) for v in info.get("rect", (0, 0, 0, 0))]
- if bw <= 0 or bh <= 0:
- continue
- x0, y0 = max(0, bx), max(0, by)
- x1, y1 = min(w - 1, bx + bw), min(h - 1, by + bh)
- ok = sc >= threshold
- if ok and name == winner:
- color = (60, 255, 60)
- elif ok:
- color = (60, 200, 60)
- else:
- color = (60, 170, 255)
- cv2.rectangle(img, (x0, y0), (x1, y1), color, 2 if ok else 1)
- label = "%s %.2f" % (name, sc)
- ty = y0 - 6 if y0 > 18 else y1 + 16
- cv2.putText(img, label, (x0 + 2, ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
- (0, 0, 0), 3, cv2.LINE_AA)
- cv2.putText(img, label, (x0 + 2, ty), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
- color, 1, cv2.LINE_AA)
- head = "threshold %.2f matches %d/%d" % (
- threshold, count_hits(per, threshold), len(per))
- cv2.putText(img, head, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
- (0, 0, 0), 4, cv2.LINE_AA)
- cv2.putText(img, head, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
- (255, 255, 255), 1, cv2.LINE_AA)
- return img
- # ---------------------------------------------------------------- 警报音
- def ensure_alarm_wav(path: Path, volume: float) -> Optional[Path]:
- """没有就现场合成一段双音警笛 wav(不用去网上找铃声)。"""
- try:
- if path.exists() and path.stat().st_size > 2000:
- return path
- path.parent.mkdir(parents=True, exist_ok=True)
- sr = 44100
- seg = []
- for _ in range(2):
- for freq in (880.0, 660.0):
- t = np.arange(int(sr * 0.22)) / sr
- tone = (0.60 * np.sin(2 * np.pi * freq * t)
- + 0.25 * np.sin(2 * np.pi * 2 * freq * t)
- + 0.12 * np.sin(2 * np.pi * 3 * freq * t))
- env = np.ones_like(t)
- n = max(1, int(sr * 0.012))
- env[:n] = np.linspace(0.0, 1.0, n)
- env[-n:] = np.linspace(1.0, 0.0, n)
- seg.append(tone * env)
- data = np.concatenate(seg)
- peak = float(np.max(np.abs(data))) or 1.0
- data = np.clip(data / peak * max(0.05, min(1.0, volume)), -1.0, 1.0)
- pcm = (data * 32767.0).astype("<i2")
- with wave.open(str(path), "wb") as fh:
- fh.setnchannels(1)
- fh.setsampwidth(2)
- fh.setframerate(sr)
- fh.writeframes(pcm.tobytes())
- return path
- except Exception:
- return None
- def speak_async(text: str) -> None:
- """用系统自带的语音合成念一句,失败就算了。"""
- def _run():
- try:
- import base64
- import subprocess
- script = (
- "Add-Type -AssemblyName System.Speech;"
- "$s=New-Object System.Speech.Synthesis.SpeechSynthesizer;"
- "$s.Rate=1;$s.Speak('%s')" % text.replace("'", "''")
- )
- enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
- subprocess.run(
- ["powershell", "-NoProfile", "-NonInteractive", "-EncodedCommand", enc],
- creationflags=0x08000000, # CREATE_NO_WINDOW
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- timeout=20,
- )
- except Exception:
- pass
- threading.Thread(target=_run, daemon=True).start()
- # ---------------------------------------------------------------- 血蓝 / 经验
- def ensure_hp_wav(path: Path, volume: float) -> Optional[Path]:
- """低血提示音:轻轻两声「叮咚」,跟测谎那种连响警笛明显不一样。"""
- try:
- if path.exists() and path.stat().st_size > 1000:
- return path
- path.parent.mkdir(parents=True, exist_ok=True)
- sr = 44100
- seg = []
- for freq, dur in ((988.0, 0.12), (0.0, 0.05), (740.0, 0.16)):
- if freq <= 0:
- seg.append(np.zeros(int(sr * dur)))
- continue
- t = np.arange(int(sr * dur)) / sr
- tone = np.sin(2 * np.pi * freq * t) + 0.2 * np.sin(2 * np.pi * 2 * freq * t)
- env = np.ones_like(t)
- n = max(1, int(sr * 0.008))
- env[:n] = np.linspace(0.0, 1.0, n)
- tail = max(1, int(sr * 0.05))
- env[-tail:] = np.linspace(1.0, 0.0, tail)
- seg.append(tone * env)
- data = np.concatenate(seg)
- peak = float(np.max(np.abs(data))) or 1.0
- data = np.clip(data / peak * max(0.05, min(1.0, volume)), -1.0, 1.0)
- pcm = (data * 32767.0).astype("<i2")
- with wave.open(str(path), "wb") as fh:
- fh.setnchannels(1)
- fh.setsampwidth(2)
- fh.setframerate(sr)
- fh.writeframes(pcm.tobytes())
- return path
- except Exception:
- return None
- class HudReader:
- """读游戏画面底部那条「HP / MP / EXP」栏。
- 这游戏用的是无抗锯齿点阵字体:同一个字每次画出来的像素完全一样
- (实测两张不同时刻的截图,同一段数字逐像素完全相等)。
- 所以这里不用 OCR,而是把每个字切成小块、跟模板逐像素比对:
- 数字是 100% 准的,也不会出现「/ 被认成 .」这种错。
- """
- GLYPHS = {"0": "0", "1": "1", "2": "2", "3": "3", "4": "4",
- "5": "5", "6": "6", "7": "7", "8": "8", "9": "9",
- "lparen": "(", "rparen": ")", "slash": "/", "dot": ".",
- "pct": "%"}
- def __init__(self, directory: Path = HUD_DIR):
- self.dir = directory
- self.by_shape: Dict[tuple, List[Tuple[str, np.ndarray]]] = {}
- self.labels: Dict[str, np.ndarray] = {}
- self.fails = 0
- self._load()
- def _load(self) -> None:
- for name, ch in self.GLYPHS.items():
- img = imread_gray(self.dir / (name + ".png"))
- if img is None:
- continue
- bits = img > 150
- self.by_shape.setdefault(bits.shape, []).append((ch, bits))
- for key in ("hp", "mp", "exp"):
- img = imread_gray(self.dir / (key + ".png"))
- if img is not None:
- self.labels[key] = img
- @property
- def ready(self) -> bool:
- return bool(self.by_shape) and len(self.labels) == 3
- # ---- 按空白列把一段文字切成一个个字
- @staticmethod
- def _segments(bits: np.ndarray, y: int, h: int, x0: int, x1: int):
- cols = bits[y:y + h, x0:x1].any(axis=0)
- out, start = [], None
- for i, on in enumerate(cols):
- if on and start is None:
- start = i
- elif not on and start is not None:
- out.append((x0 + start, x0 + i))
- start = None
- if start is not None:
- out.append((x0 + start, x1))
- return out
- def _char(self, bits, y: int, h: int, x0: int, x1: int) -> str:
- piece = bits[y:y + h, x0:x1]
- for ch, tpl in self.by_shape.get(piece.shape, ()):
- if np.array_equal(piece, tpl):
- return ch
- return "?"
- def _text(self, bits, y: int, h: int, x0: int, x1: int) -> str:
- return "".join(self._char(bits, y, h, a, b)
- for a, b in self._segments(bits, y, h, x0, x1))
- def _scaled_bits(self, scale: float) -> Dict[tuple, List[Tuple[str, np.ndarray]]]:
- """按 UI 缩放生成一份字形模板;1.0 直接复用启动时那份。"""
- if abs(scale - 1.0) < 0.03:
- return self.by_shape
- out: Dict[tuple, List[Tuple[str, np.ndarray]]] = {}
- for _shape, items in self.by_shape.items():
- for ch, bits in items:
- h, w = bits.shape
- nh = max(1, int(round(h * scale)))
- nw = max(1, int(round(w * scale)))
- img = (bits.astype(np.uint8) * 255)
- interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_NEAREST
- resized = cv2.resize(img, (nw, nh), interpolation=interp)
- rb = resized > 127
- out.setdefault(rb.shape, []).append((ch, rb))
- return out
- def _char_scaled(self, bits, y, h, x0, x1, by_shape) -> str:
- piece = bits[y:y + h, x0:x1]
- for ch, tpl in by_shape.get(piece.shape, ()):
- if np.array_equal(piece, tpl):
- return ch
- # 缩放后逐像素可能差 1px,退一步用重合率
- best_ch, best = "?", 0.0
- ph, pw = piece.shape
- for shape, items in by_shape.items():
- if abs(shape[0] - ph) > 1 or abs(shape[1] - pw) > 2:
- continue
- for ch, tpl in items:
- th, tw = tpl.shape
- hh, ww = min(ph, th), min(pw, tw)
- if hh < 1 or ww < 1:
- continue
- a = piece[:hh, :ww]
- b = tpl[:hh, :ww]
- denom = float(hh * ww)
- score = float(np.count_nonzero(a == b)) / denom
- if score > best:
- best, best_ch = score, ch
- return best_ch if best >= 0.82 else "?"
- def _text_scaled(self, bits, y, h, x0, x1, by_shape) -> str:
- return "".join(self._char_scaled(bits, y, h, a, b, by_shape)
- for a, b in self._segments(bits, y, h, x0, x1))
- # ---- 主入口:传进一帧普通灰度图(游戏客户区),返回三项,读不到就是 None
- def read(self, gray: np.ndarray,
- ui_scale: float = 1.0) -> Dict[str, Optional[tuple]]:
- out: Dict[str, Optional[tuple]] = {"hp": None, "mp": None, "exp": None}
- if not self.ready or gray is None or gray.shape[0] < 120:
- return out
- scale = float(ui_scale) if ui_scale and ui_scale > 0 else 1.0
- band = max(48, int(round(60 * max(0.7, min(1.8, scale)))))
- y0 = max(0, gray.shape[0] - band) # HUD 就贴在画面最底下
- strip = gray[y0:]
- bits = strip > 150
- by_shape = self._scaled_bits(scale)
- for key in ("hp", "mp", "exp"):
- tpl = self.labels.get(key)
- if tpl is None:
- continue
- th0, tw0 = tpl.shape[:2]
- nh = max(4, int(round(th0 * scale)))
- nw = max(4, int(round(tw0 * scale)))
- if nh >= strip.shape[0] or nw >= strip.shape[1]:
- continue
- interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_LINEAR
- tm = tpl if abs(scale - 1.0) < 0.03 else cv2.resize(
- tpl, (nw, nh), interpolation=interp)
- try:
- res = cv2.matchTemplate(strip, tm, cv2.TM_CCOEFF_NORMED)
- except cv2.error:
- continue
- _mn, score, _ml, loc = cv2.minMaxLoc(res)
- if score < 0.55:
- continue
- th, tw = tm.shape[:2]
- y, x = loc[1], loc[0] + tw
- span = min(x + max(120, int(150 * scale)), strip.shape[1])
- text = self._text_scaled(bits, y, th, x, span, by_shape)
- if key == "exp":
- m = re.match(r"(\d+)\((\d+)\.(\d+)%\)", text)
- if m:
- out["exp"] = (int(m.group(1)),
- float(m.group(2) + "." + m.group(3)))
- else:
- m = re.match(r"\((\d+)/(\d+)\)", text)
- if m and int(m.group(2)) > 0:
- out[key] = (int(m.group(1)), int(m.group(2)))
- if all(v is None for v in out.values()):
- self.fails += 1
- return out
- class HudAlert:
- """血量/蓝量过低提醒。
- 做得比测谎「轻」:短促两声 + 右上角一条小提示,不抢焦点、不切窗口,
- 也不会把测谎那套连响警笛打开——两者互不影响。
- """
- def __init__(self, cfg: dict, popup_sink=None, quiet: bool = False):
- self.cfg = cfg.get("hp_alert", {})
- self.sink = popup_sink
- self.quiet = quiet
- self.count = 0
- self._last = {"hp": 0.0, "mp": 0.0}
- self._wav = None
- if self.cfg.get("sound", True) and not quiet:
- self._wav = ensure_hp_wav(ASSET_DIR / "hp_low.wav",
- float(self.cfg.get("volume", 0.45)))
- def reset(self) -> None:
- self._last = {"hp": 0.0, "mp": 0.0}
- def check(self, now: float, hp_pct, mp_pct) -> None:
- if not self.cfg.get("enabled", True):
- return
- repeat = max(5.0, float(self.cfg.get("repeat_seconds", 30)))
- jobs = []
- if hp_pct is not None:
- low = float(self.cfg.get("low_pct", 30))
- rec = float(self.cfg.get("recover_pct", low + 5))
- if hp_pct >= rec:
- self._last["hp"] = 0.0
- elif hp_pct < low:
- if self._last["hp"] == 0.0 or now - self._last["hp"] >= repeat:
- self._last["hp"] = now
- jobs.append(("hp", hp_pct))
- if self.cfg.get("mp_enabled", True) and mp_pct is not None:
- low = float(self.cfg.get("mp_low_pct", 10))
- rec = float(self.cfg.get("mp_recover_pct", low + 5))
- if mp_pct >= rec:
- self._last["mp"] = 0.0
- elif mp_pct < low:
- if self._last["mp"] == 0.0 or now - self._last["mp"] >= repeat:
- self._last["mp"] = now
- jobs.append(("mp", mp_pct))
- for kind, pct in jobs:
- self.fire(kind, pct)
- def fire(self, kind: str, pct: float) -> None:
- self.count += 1
- label = "血量" if kind == "hp" else "蓝量"
- log("· %s只剩 %.0f%%" % (label, pct))
- if self.cfg.get("sound", True) and not self.quiet and self._wav is not None:
- try:
- import winsound
- winsound.PlaySound(str(self._wav),
- winsound.SND_FILENAME | winsound.SND_ASYNC)
- except Exception:
- pass
- if self.cfg.get("popup", True) and self.sink is not None:
- self.sink({
- "kind": kind,
- "title": "%s只剩 %.0f%%" % (label, pct),
- "text": "记得喝药 / 回城补血" if kind == "hp" else "记得补蓝",
- "seconds": float(self.cfg.get("popup_seconds", 6)),
- })
- def fmt_exp(value: Optional[float]) -> str:
- """把经验数字变成 1.23亿 / 4567万 这种好认的形式。"""
- if value is None:
- return "--"
- try:
- value = float(value)
- except Exception:
- return "--"
- if value >= 1e8:
- return "%.2f亿" % (value / 1e8)
- if value >= 1e4:
- return "%.1f万" % (value / 1e4)
- return "%d" % int(value)
- def fmt_duration(seconds: Optional[float]) -> str:
- if seconds is None or seconds <= 0 or seconds > 86400 * 30:
- return "--"
- seconds = int(seconds)
- h, m = seconds // 3600, (seconds % 3600) // 60
- if h:
- return "%d小时%d分" % (h, m)
- if m:
- return "%d分" % m
- return "%d秒" % seconds
- class ExpTrack:
- """经验采样 + 统计。
- 数据来源就是 HUD 上那个「EXP 1007297(43.89%)」:
- 当前经验 + 当前等级百分比 → 反推出这一级总共需要多少经验,
- 于是能算「还差多少」「按现在的速度还要多久升级」。
- """
- def __init__(self, cfg: dict):
- c = cfg.get("exp", {})
- self.cfg = c
- self.interval = max(2.0, float(c.get("sample_seconds", 10)))
- self.window = max(1.0, float(c.get("window_minutes", 5)))
- self.save_csv = bool(c.get("save_csv", True))
- self.samples: List[Tuple[float, int, float]] = []
- self.rate_hist: List[Tuple[float, float]] = [] # (时间, 当时算出的实时1H)
- self._last_t = 0.0
- self._seg_start = 0.0 # 当前这一级从哪个样本开始
- self._csv = None
- self._csv_day = ""
- # ---- 采样
- def feed(self, now: float, exp_val: int, exp_pct: float,
- hp=None, mp=None) -> None:
- if exp_val <= 0 or exp_pct <= 0:
- return
- if self.samples and now - self._last_t < self.interval:
- return
- prev = self.samples[-1] if self.samples else None
- if prev is not None and exp_val < prev[1]:
- # 经验变少 = 升级了(或换了角色),这一段的统计重新开始
- self._seg_start = now
- self.samples.append((now, exp_val, exp_pct))
- self._last_t = now
- self._write_csv(now, exp_val, exp_pct, hp, mp)
- return
- self.samples.append((now, exp_val, exp_pct))
- self._last_t = now
- self._trim(now)
- rate = self.rate_1h(now)
- if rate is not None:
- self.rate_hist.append((now, rate))
- cut = now - 3600
- while self.rate_hist and self.rate_hist[0][0] < cut:
- self.rate_hist.pop(0)
- self._write_csv(now, exp_val, exp_pct, hp, mp)
- def _trim(self, now: float) -> None:
- cut = now - 4 * 3600
- while self.samples and self.samples[0][0] < cut:
- self.samples.pop(0)
- def _write_csv(self, now, exp_val, exp_pct, hp, mp) -> None:
- if not self.save_csv:
- return
- try:
- day = time.strftime("%Y%m%d", time.localtime(now))
- if self._csv is None or day != self._csv_day or self._csv.closed:
- if self._csv is not None and not self._csv.closed:
- self._csv.close()
- LOG_DIR.mkdir(parents=True, exist_ok=True)
- path = LOG_DIR / ("exp_%s.csv" % day)
- new = not path.exists()
- self._csv = open(path, "a", encoding="utf-8-sig", newline="")
- self._csv_day = day
- if new:
- self._csv.write("时间,经验,百分比,实时1H,HP,MP\n")
- rate = self.rate_1h(now) or 0.0
- self._csv.write("%s,%d,%.2f,%d,%s,%s\n" % (
- time.strftime("%H:%M:%S", time.localtime(now)), exp_val,
- exp_pct, int(rate), hp if hp is not None else "",
- mp if mp is not None else ""))
- self._csv.flush()
- except Exception:
- pass
- # ---- 统计
- def _seg(self) -> List[Tuple[float, int, float]]:
- return [s for s in self.samples if s[0] >= self._seg_start]
- def rate_1h(self, now: float) -> Optional[float]:
- pts = [s for s in self.samples if now - s[0] <= self.window * 60]
- if len(pts) < 2:
- return None
- dt = pts[-1][0] - pts[0][0]
- dv = pts[-1][1] - pts[0][1]
- if dt < 20 or dv < 0:
- return None
- return dv * 3600.0 / dt
- def avg_1h(self) -> Optional[float]:
- seg = self._seg()
- if len(seg) < 2:
- return None
- dt = seg[-1][0] - seg[0][0]
- dv = seg[-1][1] - seg[0][1]
- if dt < 60 or dv < 0:
- return None
- return dv * 3600.0 / dt
- def total_exp(self) -> Optional[float]:
- if not self.samples:
- return None
- _t, val, pct = self.samples[-1]
- if pct <= 0.01:
- return None
- return val * 100.0 / pct
- def eta(self, now: float) -> Optional[float]:
- rate = self.rate_1h(now) or self.avg_1h()
- total = self.total_exp()
- if not rate or rate <= 0 or not total:
- return None
- remain = max(0.0, total - self.samples[-1][1])
- return remain / rate * 3600.0
- def close(self) -> None:
- try:
- if self._csv is not None and not self._csv.closed:
- self._csv.close()
- except Exception:
- pass
- # ---------------------------------------------------------------- 警报器
- class Alerter:
- def __init__(self, cfg: dict, popup_sink=None, quiet: bool = False):
- self.cfg = cfg.get("alert", {})
- self.popup_sink = popup_sink
- self.quiet = quiet
- self.count = 0
- self.last_text = ""
- self._wav = ensure_alarm_wav(ASSET_DIR / "alarm.wav",
- float(self.cfg.get("volume", 0.9)))
- self._sound_timer: Optional[threading.Timer] = None
- self._beeping = False
- self._beep_stop = threading.Event()
- # ---- 声音
- def _start_sound(self) -> None:
- if self.quiet:
- return
- seconds = float(self.cfg.get("sound_seconds", 10))
- try:
- import winsound
- if self._wav is not None:
- winsound.PlaySound(str(self._wav),
- winsound.SND_FILENAME | winsound.SND_ASYNC
- | winsound.SND_LOOP)
- else:
- self._start_alt_beep()
- except Exception:
- self._start_alt_beep()
- if self._sound_timer is not None:
- self._sound_timer.cancel()
- self._sound_timer = threading.Timer(seconds, self.stop_sound)
- self._sound_timer.daemon = True
- self._sound_timer.start()
- def _start_alt_beep(self) -> None:
- """wav 放不出来时,退化成系统蜂鸣。"""
- if self._beeping:
- return
- self._beeping = True
- self._beep_stop.clear()
- def _loop():
- try:
- import winsound
- while not self._beep_stop.is_set():
- winsound.Beep(1000, 300)
- winsound.Beep(700, 300)
- except Exception:
- pass
- self._beeping = False
- threading.Thread(target=_loop, daemon=True).start()
- def stop_sound(self) -> None:
- try:
- import winsound
- winsound.PlaySound(None, 0)
- except Exception:
- pass
- self._beep_stop.set()
- if self._sound_timer is not None:
- self._sound_timer.cancel()
- self._sound_timer = None
- # ---- 触发
- def fire(self, score: float, name: str, frame: Optional[np.ndarray] = None,
- manual: bool = False, per: Optional[Dict[str, dict]] = None,
- hits: int = 0) -> None:
- self.count += 1
- stamp = time.strftime("%H:%M:%S")
- self.last_text = stamp
- log("%s检测到测谎仪 相似度=%.3f 模板=%s 命中 %d/%d 个模板%s"
- % ("【测试】" if manual else "⚠ ", score, name, hits,
- len(per or {}), " (手动测试)" if manual else ""))
- if self.cfg.get("save_snapshot", True) and frame is not None and not manual:
- self._save_snapshot(frame, per, name, hits)
- if self.cfg.get("bring_to_front", True) and not manual:
- self._focus_game()
- if self.cfg.get("sound", True):
- self._start_sound()
- if self.cfg.get("voice", False) and not self.quiet:
- speak_async("注意,测谎仪出现,请立刻回到游戏")
- if self.cfg.get("popup", True) and self.popup_sink is not None:
- self.popup_sink({
- "score": score, "name": name, "time": stamp,
- "seconds": float(self.cfg.get("popup_seconds", 12)),
- "manual": manual,
- })
- def _focus_game(self) -> None:
- titles = CONFIG.get("game_window_titles", DEFAULT_CONFIG["game_window_titles"])
- hwnd, _rect = find_game_window(titles)
- if hwnd:
- force_foreground(hwnd)
- flash_window(hwnd)
- else:
- log("没找到游戏窗口,跳过切前台")
- def _save_snapshot(self, frame: np.ndarray, per: Optional[Dict[str, dict]] = None,
- name: str = "", hits: int = 0) -> None:
- try:
- LOG_DIR.mkdir(parents=True, exist_ok=True)
- path = LOG_DIR / ("hit_%s.png" % time.strftime("%Y%m%d_%H%M%S"))
- # 把匹配到的位置框出来,事后一眼看出它是认哪块画面认错的
- img = annotate(frame, per or {},
- float(CONFIG.get("threshold", 0.75)), winner=name)
- imwrite(path, img)
- shots = sorted(LOG_DIR.glob("hit_*.png"))
- for old in shots[:-40]:
- try:
- old.unlink()
- except Exception:
- pass
- except Exception:
- pass
- # ---------------------------------------------------------------- 运行时状态
- CONFIG: dict = dict(DEFAULT_CONFIG)
- class Stats:
- def __init__(self):
- self.fps = 0.0
- self.score = 0.0
- self.template = ""
- self.region = (0, 0, 0, 0)
- self.frames = 0
- self.last_alert = 0.0
- self.alerts = 0
- self.paused = False
- self.error = ""
- # 游戏窗口状态:ok = 正常;min = 最小化了;none = 没找到;screen = 监控整屏
- self.game = "none"
- # 血蓝经验(读不到就是 None / 0)
- self.hp = 0
- self.hp_max = 0
- self.mp = 0
- self.mp_max = 0
- self.exp = 0
- self.exp_pct = 0.0
- self.exp_rate = None # 实时 1H
- self.exp_avg = None # 平均 1H
- self.exp_eta = None # 预计升级还要多少秒
- self.exp_total = None # 当前等级一共要多少经验
- self.hp_alerts = 0
- self.last_hp_alert = 0.0
- # ---------------------------------------------------------------- 监控线程
- def build_matcher(cfg: dict, items: List[Template], scales=None) -> Matcher:
- return Matcher(items,
- list(scales) if scales else (cfg.get("scales") or [1.0]),
- float(cfg.get("threshold", 0.70)),
- float(cfg.get("scale_down", 2.0)))
- class Watcher(threading.Thread):
- def __init__(self, cfg: dict, store: TemplateStore, alerter: Alerter,
- stats: Stats, region_override=None, hud_alert=None, aim=None):
- super().__init__(daemon=True, name="lie-watcher")
- self.cfg = cfg
- self.store = store
- # 平时只查「画面跟模板一样大」这一档,最省 CPU;
- # 万一你的画面缩放不一样,宽范围扫描会把它找出来并记住
- self.scales = list(cfg.get("scales") or [1.0])
- self.wide_scales = list(cfg.get("scales_wide") or [])
- # 自动适应画面缩放:没命中时隔一阵子用宽档扫一遍,扫到就记住(并写进配置)
- self.auto_scale = bool(cfg.get("auto_scale", True))
- self.rescan_every = max(5, int(cfg.get("rescan_every", 40)))
- self.scale_from_hud = bool(cfg.get("scale_from_hud", True))
- self._since_wide = 0
- self.matcher = build_matcher(cfg, store.items, self.scales)
- self.alerter = alerter
- self.stats = stats
- self.region_override = region_override
- self.aim = aim # AimAssistController,测谎报警后跟红准星
- self._stop = threading.Event()
- self._last_seen = 0.0
- self._last_alert = 0.0
- self._snooze_until = 0.0
- self._hwnd = 0
- self._hwnd_at = 0.0
- self._grabber = ScreenGrabber()
- self._frame_times: List[float] = []
- self._confirm_streak = 0
- self._ui_scale = float((self.scales or [1.0])[0])
- self._scale_probed = False
- self._last_client_size = (0, 0)
- # 血蓝:读游戏底部那条 HUD
- self.hud = None
- if cfg.get("hud", {}).get("enabled", True):
- reader = HudReader()
- if reader.ready:
- self.hud = reader
- else:
- log("templates/hud 里没有字形模板,血量/经验功能关闭")
- self.hud_alert = hud_alert
- # 经验统计
- self.exp = ExpTrack(cfg) if cfg.get("exp", {}).get("enabled") else None
- self._hud_at = 0.0
- # ---- 外部控制
- def stop(self) -> None:
- self._stop.set()
- def snooze(self, seconds: float) -> None:
- self._snooze_until = time.time() + seconds
- def apply_scale(self, scales: List[float], auto: bool) -> None:
- """设置页改了缩放:立刻换一套档位重新查,不用重启。"""
- new = [float(s) for s in (scales or [1.0])]
- auto = bool(auto)
- changed = (new != self.scales) or (auto != self.auto_scale)
- self.scales = new
- self.auto_scale = auto
- self._ui_scale = float(new[len(new) // 2] if new else 1.0)
- if changed:
- self.matcher = build_matcher(self.cfg, self.store.items, self.scales)
- self._since_wide = 0
- self._scale_probed = False
- log("缩放档位已改为 %s%s"
- % (["x%.2f" % s for s in self.scales],
- "(自动适应)" if self.auto_scale else "(固定)"))
- self.alerter.stop_sound()
- def test_alert(self) -> None:
- self.alerter.fire(1.0, "手动测试", manual=True)
- if self.aim is not None:
- self.aim.trigger(manual=True)
- def aim_region(self) -> Optional[Tuple[int, int, int, int]]:
- """瞄准用的游戏客户区屏幕矩形;找不到游戏就返回 None。"""
- titles = self.cfg.get("game_window_titles", DEFAULT_CONFIG["game_window_titles"])
- if self._hwnd:
- try:
- x, y, w, h = client_rect(self._hwnd)
- if w >= 320 and h >= 240:
- return (int(x), int(y), int(w), int(h))
- except Exception:
- self._hwnd = 0
- hwnd, rect = find_game_window(titles)
- if hwnd and rect:
- self._hwnd = hwnd
- return (int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3]))
- return None
- # ---- 区域
- def _region(self) -> Tuple[int, int, int, int]:
- titles = self.cfg.get("game_window_titles", DEFAULT_CONFIG["game_window_titles"])
- if self.region_override:
- self.stats.game = "screen"
- return clamp_region(self.region_override)
- if self.cfg.get("capture") == "screen":
- self.stats.game = "screen"
- return clamp_region(virtual_screen())
- now = time.time()
- if now - self._hwnd_at > 2.0 or not self._hwnd:
- self._hwnd, _rect = find_game_window(titles)
- self._hwnd_at = now
- if self._hwnd:
- try:
- x, y, w, h = client_rect(self._hwnd)
- if w >= 320 and h >= 240:
- self.stats.game = "ok"
- return clamp_region((x, y, w, h))
- except Exception:
- self._hwnd = 0
- # 没找到游戏窗口:要么最小化了,要么根本没开
- self.stats.game = ("min" if game_window_minimized(titles) else "none")
- self.stats.hp = self.stats.hp_max = 0
- self.stats.mp = self.stats.mp_max = 0
- self.stats.exp = 0.0
- self.stats.exp_pct = 0.0
- return clamp_region(virtual_screen())
- # ---- 血蓝 / 经验
- def _update_hud(self, gray: np.ndarray, now: float) -> None:
- st = self.stats
- if st.game != "ok":
- # 画面不是游戏客户区(没开 / 最小化 / 整屏兜底)就别拿旧数字乱报警
- return
- vals = self.hud.read(gray, ui_scale=self._ui_scale)
- hp, mp, exp = vals.get("hp"), vals.get("mp"), vals.get("exp")
- if hp and hp[1] > 0:
- st.hp, st.hp_max = hp[0], hp[1]
- if mp and mp[1] > 0:
- st.mp, st.mp_max = mp[0], mp[1]
- if exp:
- st.exp, st.exp_pct = exp[0], exp[1]
- if self.exp is not None and exp:
- self.exp.feed(now, exp[0], exp[1], st.hp or None, st.mp or None)
- st.exp_rate = self.exp.rate_1h(now)
- st.exp_avg = self.exp.avg_1h()
- st.exp_eta = self.exp.eta(now)
- st.exp_total = self.exp.total_exp()
- if self.hud_alert is not None:
- hp_pct = (st.hp * 100.0 / st.hp_max) if st.hp_max else None
- mp_pct = (st.mp * 100.0 / st.mp_max) if st.mp_max else None
- before = self.hud_alert.count
- self.hud_alert.check(now, hp_pct, mp_pct)
- if self.hud_alert.count != before:
- st.hp_alerts = self.hud_alert.count
- st.last_hp_alert = now
- def _remember_scales(self, center: float, reason: str) -> None:
- """把推算出的 UI 缩放写成三档附近搜索,并持久化。"""
- center = float(center)
- new_scales = sorted({round(center * k, 3) for k in (0.96, 1.0, 1.04)})
- self._ui_scale = center
- if new_scales == self.scales:
- return
- self.scales = new_scales
- self.matcher = build_matcher(self.cfg, self.store.items, self.scales)
- try:
- self.cfg["scales"] = new_scales
- save_config(self.cfg)
- except Exception:
- pass
- log("画面缩放和模板不一样,已按 x%.2f 调整档位:%s(%s,已记住)"
- % (center, self.scales, reason))
- def _probe_ui_scale(self, gray: np.ndarray, force: bool = False) -> None:
- """启动后 / 窗口尺寸变化时,用 HUD 标签推一把 UI 缩放。"""
- if not self.auto_scale or not self.scale_from_hud:
- return
- if self.hud is None or not self.hud.labels:
- return
- if self._scale_probed and not force:
- return
- wide = list(self.cfg.get("scales_wide") or self.wide_scales or [])
- est = estimate_ui_scale(gray, self.hud.labels, wide or None)
- self._scale_probed = True
- if est is None:
- return
- if abs(est - self._ui_scale) >= 0.04 or abs(est - 1.0) >= 0.06:
- self._remember_scales(est, "按底部HP标签推算")
- else:
- self._ui_scale = est
- def _judge(self, hit, per, threshold: float):
- """返回 (confirmed, hard_hits_in_cluster)。"""
- min_hits = max(1, int(self.cfg.get("min_hits", 2)))
- strong = float(self.cfg.get("strong_threshold", 0.92))
- require_layout = bool(self.cfg.get("require_layout", True))
- pair_avg = float(self.cfg.get("pair_avg_threshold", 0.82))
- clustered = cluster_hits(per, threshold) if require_layout \
- else _hit_items(per, threshold)
- hits = sum(1 for _, v in clustered
- if float(v.get("score", 0.0)) >= threshold)
- ok = is_confirmed(hit, per, threshold, min_hits, strong,
- require_layout=require_layout, pair_avg=pair_avg)
- return ok, hits
- # ---- 主循环
- def run(self) -> None:
- interval = 1.0 / max(1.0, float(self.cfg.get("max_fps", 6)))
- repeat = float(self.cfg.get("alert_repeat_seconds", 15))
- threshold = float(self.cfg.get("threshold", 0.75))
- log("开始监控:%d 个模板,阈值 %.2f,目标 %d 帧/秒"
- % (len(self.store.items), threshold, int(1 / interval)))
- # 想看每帧到底花多少时间,就设环境变量 LIE_TRACE=1 再运行
- trace = bool(os.environ.get("LIE_TRACE"))
- if trace:
- log("调试模式:逐帧打印抓屏/识别耗时")
- while not self._stop.is_set():
- # 帧率/阈值每帧现读:设置页改完不用重启就生效
- interval = 1.0 / max(1.0, float(self.cfg.get("max_fps", 6)))
- threshold = float(self.cfg.get("threshold", 0.75))
- need_frames = max(1, int(self.cfg.get("confirm_frames", 2)))
- started = time.perf_counter()
- if self.stats.paused:
- time.sleep(0.15)
- continue
- if self.store.maybe_reload():
- self.matcher = build_matcher(self.cfg, self.store.items,
- self.scales)
- log("模板已更新:%d 个" % len(self.store.items))
- region = self._region()
- self.stats.region = region
- # 没游戏窗口 / 游戏最小化了就待机:整屏画面里什么都有,
- # 拿它去认模板特别容易误报(浏览器工具栏那种就是),干脆不认。
- if self.stats.game in ("none", "min"):
- self.stats.score = 0.0
- self._confirm_streak = 0
- time.sleep(max(interval, 0.4))
- continue
- t0 = time.perf_counter()
- gray = self._grabber.grab_gray(*region)
- t1 = time.perf_counter()
- if gray is None:
- self.stats.error = "抓屏失败"
- time.sleep(0.5)
- continue
- client_size = (int(region[2]), int(region[3]))
- if client_size != self._last_client_size:
- # 分辨率/窗口大小变了:重新用 HUD 推缩放
- if self._last_client_size != (0, 0):
- self._scale_probed = False
- self._last_client_size = client_size
- self._probe_ui_scale(gray)
- hit, per = self.matcher.match(gray)
- t2 = time.perf_counter()
- if self.hud is not None:
- self._update_hud(gray, time.time())
- self._since_wide += 1
- confirmed, hits = self._judge(hit, per, threshold)
- # 没确认命中时,隔一阵子把缩放档位放宽扫一遍:
- # 既兜住「画面缩放跟模板不一样」的情况,扫到了就记住,以后按这个档位查
- if (not confirmed and self.auto_scale
- and self._since_wide >= self.rescan_every
- and len(self.wide_scales) > 1):
- self._since_wide = 0
- wide = build_matcher(self.cfg, self.store.items, self.wide_scales)
- wh, wper = wide.match(gray, early_exit=False)
- if wh.score >= threshold * 0.9:
- hit, per = wh, wper
- confirmed, hits = self._judge(hit, per, threshold)
- if (wh.score >= max(threshold, 0.80)
- and abs(wh.scale - self._ui_scale) > 0.06):
- self._remember_scales(wh.scale, "宽范围扫描")
- self.stats.score = hit.score
- self.stats.template = hit.name
- self.stats.frames += 1
- if trace:
- log("帧 %d:区域 %dx%d 抓屏 %.0fms 识别 %.0fms 分数 %.3f 命中 %d/%d%s"
- % (self.stats.frames, region[2], region[3],
- (t1 - t0) * 1000.0, (t2 - t1) * 1000.0, hit.score,
- hits, len(per),
- (" ← " + hit.name) if confirmed else ""))
- if confirmed:
- self._confirm_streak += 1
- else:
- self._confirm_streak = 0
- if confirmed and self._confirm_streak >= need_frames:
- now = time.time()
- gap = now - self._last_seen if self._last_seen else 1e9
- self._last_seen = now
- due = (self._last_alert == 0.0 or gap >= repeat
- or (now - self._last_alert) >= repeat)
- if due and now >= self._snooze_until:
- self._last_alert = now
- self.stats.last_alert = now
- self.stats.alerts += 1
- self.alerter.fire(hit.score, hit.name, frame=gray,
- per=per, hits=hits)
- # 报警后立刻开 YOLO+ByteTrack,用 Interception 跟红准星
- if self.aim is not None:
- try:
- self.aim.trigger(manual=False)
- except Exception as exc:
- log("启动瞄准失败:%s" % exc)
- elif trace and hit.score >= threshold:
- log("未确认报警:命中 %d 连续 %d/%d(%s %.3f)"
- % (hits, self._confirm_streak, need_frames,
- hit.name, hit.score))
- elapsed = time.perf_counter() - started
- # 单帧真实占用 = 干活的时间 + 为了限速而睡的时间
- total = elapsed if elapsed > interval else interval
- self._frame_times.append(total)
- if len(self._frame_times) > 20:
- self._frame_times.pop(0)
- avg = sum(self._frame_times) / len(self._frame_times)
- self.stats.fps = 1.0 / avg if avg > 0 else 0.0
- wait = interval - elapsed
- if wait > 0:
- time.sleep(wait)
- # ---------------------------------------------------------------- 界面
- class StatusApp:
- """状态小窗 + 红色提醒窗。Tk 必须在主线程。"""
- def __init__(self, ctl: "Controller"):
- import tkinter as tk
- self.tk = tk
- self.ctl = ctl
- self.popup = None
- self._popup_after = None
- self._popup_info = None
- self.toast = None
- self._toast_after = None
- self.exp_win = None
- self._exp_texts = None
- self._exp_canvas = None
- self.settings = None
- root = tk.Tk()
- self.root = root
- root.title(APP_NAME)
- root.resizable(False, False)
- root.configure(bg="#1f1f1f")
- root.protocol("WM_DELETE_WINDOW", self._on_quit)
- sw = root.winfo_screenwidth()
- sh = root.winfo_screenheight()
- W, H = 340, 224
- x, y = max(0, sw - W - 30), max(0, sh - H - 80)
- # 优先摆在游戏窗口右边/下边,尽量别挡住游戏画面
- try:
- hwnd, _r = find_game_window(ctl.cfg.get("game_window_titles", []))
- if hwnd:
- gx, gy, gw, gh = client_rect(hwnd)
- rx = min(max(0, gx + gw - W), sw - W - 10)
- if gw > 200 and gx + gw + W + 8 <= sw:
- x, y = gx + gw + 6, gy # 游戏右边
- elif gw > 200 and gy + gh + H + 8 <= sh:
- x, y = rx, gy + gh + 6 # 游戏下边
- elif gw > 200 and gy - H - 8 >= 0:
- x, y = rx, gy - H - 8 # 游戏上边
- except Exception:
- pass
- root.geometry("%dx%d+%d+%d" % (W, H, x, y))
- try:
- root.attributes("-topmost", bool(ctl.cfg.get("status_on_top", False)))
- except Exception:
- pass
- font = ("Microsoft YaHei UI", 10)
- title = tk.Label(root, text="冒险岛 · 测谎仪提醒", bg="#1f1f1f", fg="#f0c040",
- font=("Microsoft YaHei UI", 12, "bold"))
- title.pack(pady=(10, 4))
- # 右上角那颗齿轮:点开设置页
- self.gear = tk.Label(root, text="⚙", bg="#1f1f1f", fg="#8a8a8a",
- font=("Segoe UI Symbol", 13), cursor="hand2")
- self.gear.place(relx=1.0, x=-10, y=6, anchor="ne")
- self.gear.bind("<Button-1>", lambda _e: self._open_settings())
- self.gear.bind("<Enter>", lambda _e: self.gear.config(fg="#f0c040"))
- self.gear.bind("<Leave>", lambda _e: self.gear.config(fg="#8a8a8a"))
- self.lbl_state = tk.Label(root, text="正在启动…", bg="#1f1f1f", fg="#7ed321",
- font=("Microsoft YaHei UI", 11, "bold"))
- self.lbl_state.pack()
- self.lbl_info = tk.Label(root, text="", bg="#1f1f1f", fg="#cccccc", font=font,
- justify="center")
- self.lbl_info.pack(pady=(2, 6))
- bar = tk.Frame(root, bg="#1f1f1f")
- bar.pack()
- self.btn_pause = tk.Button(bar, text="暂停", width=6, command=self._toggle_pause,
- font=font)
- self.btn_pause.pack(side="left", padx=3)
- tk.Button(bar, text="测试", width=6, command=self._test,
- font=font).pack(side="left", padx=3)
- self.btn_exp = tk.Button(bar, text="经验", width=6, command=self._toggle_exp,
- font=font)
- self.btn_exp.pack(side="left", padx=3)
- tk.Button(bar, text="退出", width=5, command=self._on_quit,
- font=font).pack(side="left", padx=3)
- self._poll()
- # 开了经验统计就把统计小窗一起打开
- exp_cfg = ctl.cfg.get("exp", {})
- if exp_cfg.get("enabled") and exp_cfg.get("window", True):
- self.root.after(600, self._open_exp_window)
- # ---- 轮询
- def _poll(self) -> None:
- st = self.ctl.stats
- try:
- while True:
- ev = self.ctl.events.get_nowait()
- if ev[0] == "alert":
- self._show_popup(ev[1])
- elif ev[0] == "toast":
- self._show_toast(ev[1])
- except queue.Empty:
- pass
- if st.paused:
- self.lbl_state.config(text="⏸ 已暂停", fg="#f0c040")
- elif st.error:
- self.lbl_state.config(text="⚠ " + st.error, fg="#ff5555")
- elif st.game == "none":
- self.lbl_state.config(text="○ 等游戏窗口…", fg="#f0c040")
- elif st.game == "min":
- self.lbl_state.config(text="○ 游戏最小化了", fg="#f0c040")
- else:
- self.lbl_state.config(text="● 监控中", fg="#7ed321")
- lines = []
- if st.hp_max > 0:
- hp_pct = st.hp * 100.0 / st.hp_max
- mp_txt = ""
- if st.mp_max > 0:
- mp_txt = " MP %.0f%%" % (st.mp * 100.0 / st.mp_max)
- lines.append("HP %.0f%% (%d/%d)%s" % (hp_pct, st.hp, st.hp_max, mp_txt))
- if st.exp_pct > 0:
- bits = ["EXP %.2f%%" % st.exp_pct]
- if st.exp_rate:
- bits.append("1H %s" % fmt_exp(st.exp_rate))
- if st.exp_eta:
- bits.append("升级约 %s" % fmt_duration(st.exp_eta))
- lines.append(" · ".join(bits))
- last = ("--:--:--" if not st.last_alert
- else time.strftime("%H:%M:%S", time.localtime(st.last_alert)))
- tail = ["%.1f 帧/秒" % st.fps, "%.2f" % st.score,
- "测谎 %d" % st.alerts]
- if st.hp_alerts:
- tail.append("低血 %d" % st.hp_alerts)
- tail.append(last)
- lines.append(" · ".join(tail))
- self.lbl_info.config(text="\n".join(lines))
- self._update_exp_window()
- self.root.after(200, self._poll)
- # ---- 按钮
- def _toggle_pause(self) -> None:
- self.ctl.stats.paused = not self.ctl.stats.paused
- self.btn_pause.config(text="继续" if self.ctl.stats.paused else "暂停")
- def _open_settings(self) -> None:
- if self.settings is not None:
- try:
- self.settings.top.deiconify()
- self.settings.top.lift()
- return
- except Exception:
- self.settings = None
- try:
- self.settings = SettingsWindow(self.ctl, self.root)
- except Exception as exc:
- log("打开设置失败:%s" % exc)
- def _test(self) -> None:
- self.ctl.watcher.test_alert()
- def _on_quit(self) -> None:
- try:
- self.ctl.stop()
- finally:
- self.root.destroy()
- # ---- 红色提醒窗
- def _show_popup(self, info: dict) -> None:
- tk = self.tk
- if self.popup is not None and self.popup.winfo_exists():
- try:
- self.popup.lift()
- self.popup.attributes("-topmost", True)
- if self._popup_after is not None:
- self.popup.after_cancel(self._popup_after)
- except Exception:
- pass
- else:
- win = tk.Toplevel(self.root)
- win.overrideredirect(True)
- win.attributes("-topmost", True)
- win.configure(bg="#c00000", cursor="hand2")
- width, height = 430, 186
- sw = self.root.winfo_screenwidth()
- win.geometry("%dx%d+%d+%d" % (width, height,
- max(0, (sw - width) // 2), 28))
- box = tk.Frame(win, bg="#c00000")
- box.pack(expand=True, fill="both", padx=14, pady=10)
- tk.Label(box, text="⚠ 测谎仪!", bg="#c00000", fg="#ffffff",
- font=("Microsoft YaHei UI", 26, "bold")).pack(pady=(4, 0))
- tk.Label(box, text="快回游戏,把鼠标放到图形上", bg="#c00000",
- fg="#ffe9a8", font=("Microsoft YaHei UI", 13, "bold")).pack(pady=(2, 4))
- self._lbl_sub = tk.Label(box, text="", bg="#c00000", fg="#ffd0d0",
- font=("Microsoft YaHei UI", 9))
- self._lbl_sub.pack()
- tk.Label(box, text="点一下这里关掉", bg="#c00000", fg="#ffb0b0",
- font=("Microsoft YaHei UI", 8)).pack(pady=(4, 0))
- for widget in (win, box) + tuple(box.winfo_children()):
- widget.bind("<Button-1>", lambda _e: self._dismiss_popup())
- self.popup = win
- text = "%s · 相似度 %.2f · %s" % (
- "手动测试" if info.get("manual") else "已提醒", info.get("score", 0.0),
- info.get("time", ""))
- try:
- self._lbl_sub.config(text=text)
- except Exception:
- pass
- seconds = max(3.0, float(info.get("seconds", 12)))
- self._popup_after = self.popup.after(int(seconds * 1000), self._dismiss_popup)
- def _dismiss_popup(self) -> None:
- if self.popup is None:
- return
- try:
- self.popup.destroy()
- except Exception:
- pass
- self.popup = None
- self._popup_after = None
- snooze = float(self.ctl.cfg.get("alert", {}).get("snooze_seconds", 60))
- self.ctl.watcher.snooze(snooze)
- # ---- 低血/低蓝的小提示条(不抢焦点、不切窗口)
- def _show_toast(self, info: dict) -> None:
- tk = self.tk
- if self.toast is not None and self.toast.winfo_exists():
- try:
- self.toast.destroy()
- except Exception:
- pass
- self.toast = None
- win = tk.Toplevel(self.root)
- win.overrideredirect(True)
- win.attributes("-topmost", True)
- win.configure(bg="#7a3b00", cursor="hand2")
- w, h = 300, 84
- try:
- x = self.root.winfo_x()
- y = self.root.winfo_y() + self.root.winfo_height() + 8
- # 经验统计小窗也贴在下面时,提示条让到它下方,免得互相盖住
- if self.exp_win is not None and self.exp_win.winfo_exists():
- y = max(y, self.exp_win.winfo_y() + self.exp_win.winfo_height() + 40)
- except Exception:
- x, y = 40, 40
- sw, sh = win.winfo_screenwidth(), win.winfo_screenheight()
- x = min(max(0, x), max(0, sw - w - 10))
- y = min(max(0, y), max(0, sh - h - 50))
- win.geometry("%dx%d+%d+%d" % (w, h, x, y))
- tk.Label(win, text="⚠ " + str(info.get("title", "")), bg="#7a3b00",
- fg="#ffd9a8",
- font=("Microsoft YaHei UI", 13, "bold")).pack(pady=(10, 2))
- tk.Label(win, text=str(info.get("text", "")), bg="#7a3b00", fg="#ffbf80",
- font=("Microsoft YaHei UI", 9)).pack()
- for widget in (win,) + tuple(win.winfo_children()):
- widget.bind("<Button-1>", lambda _e: self._dismiss_toast())
- self.toast = win
- self._toast_after = win.after(
- int(max(2.0, float(info.get("seconds", 6))) * 1000), self._dismiss_toast)
- def _dismiss_toast(self) -> None:
- if self.toast is None:
- return
- try:
- self.toast.destroy()
- except Exception:
- pass
- self.toast = None
- self._toast_after = None
- # ---- 经验统计小窗
- def _toggle_exp(self) -> None:
- if self.exp_win is not None:
- try:
- if self.exp_win.winfo_exists():
- self.exp_win.destroy()
- self.exp_win = None
- return
- except Exception:
- pass
- self.exp_win = None
- self._open_exp_window()
- def _open_exp_window(self) -> None:
- tk = self.tk
- win = tk.Toplevel(self.root)
- win.title("经验统计")
- win.resizable(False, False)
- win.configure(bg="#1f1f1f")
- w, h = 396, 268
- try:
- # 优先贴在状态窗右侧,其次下方(右边和下方都在游戏画面之外),
- # 最后才放左边——放左边会盖住游戏区域。
- sw, sh = win.winfo_screenwidth(), win.winfo_screenheight()
- x = self.root.winfo_x() + self.root.winfo_width() + 8
- y = self.root.winfo_y()
- if x + w > sw:
- x = self.root.winfo_x()
- y = self.root.winfo_y() + self.root.winfo_height() + 8
- if y + h > sh:
- y = max(0, sh - h - 10)
- if x + w > sw:
- x = max(0, sw - w - 10)
- except Exception:
- x, y = 40, 40
- win.geometry("%dx%d+%d+%d" % (w, h, x, y))
- font = ("Microsoft YaHei UI", 10)
- head = tk.Frame(win, bg="#1f1f1f")
- head.pack(fill="x", padx=12, pady=(10, 2))
- tk.Label(head, text="经验统计", bg="#1f1f1f", fg="#f0c040",
- font=("Microsoft YaHei UI", 12, "bold")).pack(side="left")
- tk.Label(head, text="数据存 logs\\exp_*.csv", bg="#1f1f1f", fg="#777777",
- font=("Microsoft YaHei UI", 8)).pack(side="right")
- grid = tk.Frame(win, bg="#1f1f1f")
- grid.pack(fill="x", padx=12)
- texts = {}
- for i, (key, label) in enumerate((
- ("now", "当前经验"), ("rate", "实时 1H"), ("avg", "平均 1H"),
- ("remain", "这级还差"), ("eta", "预计升级"))):
- tk.Label(grid, text=label, bg="#1f1f1f", fg="#999999", font=font,
- anchor="w", width=8).grid(row=i // 2, column=(i % 2) * 2,
- sticky="w", padx=(0, 2), pady=1)
- lb = tk.Label(grid, text="--", bg="#1f1f1f", fg="#dddddd", font=font,
- anchor="w", width=16)
- lb.grid(row=i // 2, column=(i % 2) * 2 + 1, sticky="w", padx=(0, 10), pady=1)
- texts[key] = lb
- self._exp_texts = texts
- cv = tk.Canvas(win, width=372, height=96, bg="#111111",
- highlightthickness=0)
- cv.pack(padx=12, pady=(8, 4))
- self._exp_canvas = cv
- tk.Label(win, text="最近 1 小时的实时 1H 经验走势", bg="#1f1f1f",
- fg="#777777", font=("Microsoft YaHei UI", 8)).pack()
- self.exp_win = win
- def _update_exp_window(self) -> None:
- if self.exp_win is None:
- return
- try:
- if not self.exp_win.winfo_exists():
- self.exp_win = None
- return
- except Exception:
- self.exp_win = None
- return
- st = self.ctl.stats
- texts = self._exp_texts or {}
- remain = None
- if st.exp_total and st.exp:
- remain = max(0.0, st.exp_total - st.exp)
- values = {
- "now": "%s (%.2f%%)" % (fmt_exp(st.exp), st.exp_pct),
- "rate": ("%s / 时" % fmt_exp(st.exp_rate)) if st.exp_rate else "--",
- "avg": ("%s / 时" % fmt_exp(st.exp_avg)) if st.exp_avg else "--",
- "remain": fmt_exp(remain),
- "eta": fmt_duration(st.exp_eta),
- }
- for key, lb in texts.items():
- try:
- lb.config(text=values.get(key, "--"))
- except Exception:
- pass
- if self._exp_canvas is not None:
- try:
- self._draw_chart(self._exp_canvas)
- except Exception:
- pass
- def _draw_chart(self, cv) -> None:
- W, H = 372, 96
- cv.delete("all")
- cv.create_rectangle(0, 0, W, H, fill="#111111", outline="")
- for i in range(1, 4):
- y = H * i / 4.0
- cv.create_line(0, y, W, y, fill="#262626")
- tracker = getattr(self.ctl.watcher, "exp", None)
- hist = list(getattr(tracker, "rate_hist", []) or []) if tracker else []
- now = time.time()
- pts = [(t, v) for t, v in hist if now - t <= 3600]
- if len(pts) < 2:
- cv.create_text(W // 2, H // 2, text="再挂一会儿就有走势了",
- fill="#777777", font=("Microsoft YaHei UI", 9))
- return
- t0 = max(now - 3600, pts[0][0])
- span = max(60.0, pts[-1][0] - t0)
- vmax = max(v for _t, v in pts) or 1.0
- coords = []
- for t, v in pts:
- x = (t - t0) / span * (W - 10) + 5
- y = H - 10 - (v / vmax) * (H - 26)
- coords.extend((x, y))
- cv.create_line(*coords, fill="#7ed321", width=2)
- cv.create_text(6, 8, text="峰值 %s / 时" % fmt_exp(vmax), anchor="w",
- fill="#9be36b", font=("Microsoft YaHei UI", 8))
- def run(self) -> None:
- self.root.mainloop()
- # ---------------------------------------------------------------- 设置页
- class SettingsWindow:
- """齿轮按钮打开的设置页:勾一勾、改个数,保存就写回 config.json。"""
- def __init__(self, ctl: "Controller", master):
- import tkinter as tk
- self.tk = tk
- self.ctl = ctl
- self.cfg = ctl.cfg
- self.font = ("Microsoft YaHei UI", 9)
- self.vars: Dict[str, object] = {}
- alert = self.cfg.get("alert", {})
- hp = self.cfg.get("hp_alert", {})
- exp = self.cfg.get("exp", {})
- top = tk.Toplevel(master)
- self.top = top
- top.title("设置")
- top.configure(bg="#1f1f1f")
- top.resizable(False, False)
- top.transient(master)
- try:
- top.attributes("-topmost", True)
- except Exception:
- pass
- top.protocol("WM_DELETE_WINDOW", self._close)
- # ---- 测谎提醒
- self._section("测谎提醒")
- r = self._row()
- self._check(r, "声音", "alert_sound", bool(alert.get("sound", True)))
- self._label(r, "响")
- self._spin(r, "alert_sound_seconds", alert.get("sound_seconds", 10),
- 3, 120, 1, 4, "%.0f")
- self._label(r, "秒 音量")
- self._spin(r, "alert_volume", alert.get("volume", 0.9),
- 0.1, 1.0, 0.1, 4, "%.2f")
- r = self._row()
- self._check(r, "红色大弹窗", "alert_popup", bool(alert.get("popup", True)))
- self._label(r, "停留")
- self._spin(r, "alert_popup_seconds", alert.get("popup_seconds", 12),
- 3, 120, 1, 4, "%.0f")
- self._label(r, "秒")
- r = self._row()
- self._check(r, "报警时切到游戏", "bring_to_front",
- bool(alert.get("bring_to_front", True)))
- self._label(r, " ")
- self._check(r, "保存现场截图", "save_snapshot",
- bool(alert.get("save_snapshot", True)))
- r = self._row()
- self._label(r, "相似度阈值", pad=(0, 2))
- self._spin(r, "threshold", self.cfg.get("threshold", 0.75),
- 0.5, 0.99, 0.01, 5, "%.2f")
- self._label(r, " 至少")
- self._spin(r, "min_hits", self.cfg.get("min_hits", 2), 1, 4, 1, 3, "%.0f")
- self._label(r, "个模板 每秒")
- self._spin(r, "max_fps", self.cfg.get("max_fps", 5), 1, 15, 1, 3, "%.0f")
- self._label(r, "次")
- r = self._row()
- self._label(r, "连续确认", pad=(0, 2))
- self._spin(r, "confirm_frames", self.cfg.get("confirm_frames", 2),
- 1, 5, 1, 3, "%.0f")
- self._label(r, "帧 ")
- self._check(r, "布局校验(防误报)", "require_layout",
- bool(self.cfg.get("require_layout", True)))
- r = self._row()
- self._check(r, "自动适应画面缩放", "auto_scale",
- bool(self.cfg.get("auto_scale", True)))
- self._label(r, " 固定 x")
- cur_scale = float((self.cfg.get("scales") or [1.0])[0])
- self._spin(r, "scale_value", cur_scale, 0.5, 2.0, 0.01, 5, "%.2f")
- # ---- 血量 / 蓝量
- self._section("血量 / 蓝量")
- r = self._row()
- self._check(r, "血量提醒", "hp_enabled", bool(hp.get("enabled", True)))
- self._label(r, "低于")
- self._spin(r, "hp_low", hp.get("low_pct", 30), 1, 95, 1, 3, "%.0f")
- self._label(r, "% 回到")
- self._spin(r, "hp_recover", hp.get("recover_pct", 35), 1, 99, 1, 3, "%.0f")
- self._label(r, "% 停")
- r = self._row()
- self._check(r, "蓝量提醒", "mp_enabled", bool(hp.get("mp_enabled", True)))
- self._label(r, "低于")
- self._spin(r, "mp_low", hp.get("mp_low_pct", 10), 1, 95, 1, 3, "%.0f")
- self._label(r, "% 回到")
- self._spin(r, "mp_recover", hp.get("mp_recover_pct", 15), 1, 99, 1, 3, "%.0f")
- self._label(r, "% 停")
- r = self._row()
- self._label(r, "重复提醒间隔", pad=(0, 2))
- self._spin(r, "hp_repeat", hp.get("repeat_seconds", 30), 5, 300, 5, 4, "%.0f")
- self._label(r, "秒 ")
- self._check(r, "提示音", "hp_sound", bool(hp.get("sound", True)))
- self._label(r, "音量")
- self._spin(r, "hp_volume", hp.get("volume", 0.45), 0.1, 1.0, 0.1, 4, "%.2f")
- # ---- 经验统计
- self._section("经验统计")
- r = self._row()
- self._check(r, "记录经验", "exp_enabled", bool(exp.get("enabled", False)))
- self._label(r, " ")
- self._check(r, "打开统计小窗", "exp_window", bool(exp.get("window", True)))
- r = self._row()
- self._label(r, "采样间隔", pad=(0, 2))
- self._spin(r, "exp_sample", exp.get("sample_seconds", 10), 5, 120, 5, 4, "%.0f")
- self._label(r, "秒(越大越省 CPU)")
- # ---- 瞄准(YOLO + Interception)
- aim = self.cfg.get("aim_assist", {})
- self._section("测谎瞄准(YOLO+ByteTrack)")
- r = self._row()
- self._check(r, "报警后自动瞄准", "aim_enabled", bool(aim.get("enabled", True)))
- self._label(r, " 最长")
- self._spin(r, "aim_duration", aim.get("duration_seconds", 25), 5, 120, 1, 4, "%.0f")
- self._label(r, "秒")
- r = self._row()
- self._check(r, "测试按钮也开瞄准", "aim_on_manual",
- bool(aim.get("on_manual_test", False)))
- self._label(r, " 调试预览窗")
- self._check(r, "开", "aim_overlay", bool(aim.get("show_overlay", False)))
- # ---- 底部按钮
- bar = tk.Frame(top, bg="#1f1f1f")
- bar.pack(fill="x", padx=14, pady=(16, 12))
- tk.Button(bar, text="恢复默认", width=8, command=self._restore,
- font=self.font).pack(side="left")
- tk.Button(bar, text="保存", width=8, command=self._save,
- font=("Microsoft YaHei UI", 9, "bold")).pack(side="right")
- tk.Button(bar, text="取消", width=8, command=self._close,
- font=self.font).pack(side="right", padx=8)
- top.update_idletasks()
- w, h = top.winfo_width(), top.winfo_height()
- sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
- x = max(0, min(master.winfo_x() - w - 10, sw - w - 10))
- if x < 10:
- x = (sw - w) // 2
- y = max(0, min(master.winfo_y(), sh - h - 40))
- top.geometry("+%d+%d" % (x, y))
- top.grab_set()
- # ---- 搭界面用的小工具
- def _section(self, text: str) -> None:
- tk = self.tk
- f = tk.Frame(self.top, bg="#1f1f1f")
- f.pack(fill="x", padx=14, pady=(12, 2))
- tk.Label(f, text=text, bg="#1f1f1f", fg="#f0c040",
- font=("Microsoft YaHei UI", 10, "bold")).pack(anchor="w")
- def _row(self):
- tk = self.tk
- f = tk.Frame(self.top, bg="#1f1f1f")
- f.pack(fill="x", padx=14)
- return f
- def _check(self, parent, text: str, key: str, value: bool):
- tk = self.tk
- var = tk.BooleanVar(value=bool(value))
- self.vars[key] = var
- c = tk.Checkbutton(parent, text=text, variable=var, bg="#1f1f1f",
- fg="#dddddd", selectcolor="#2a2a2a",
- activebackground="#1f1f1f", activeforeground="#ffffff",
- font=self.font, bd=0, highlightthickness=0)
- c.pack(side="left")
- return c
- def _label(self, parent, text: str, pad=(8, 2)):
- self.tk.Label(parent, text=text, bg="#1f1f1f", fg="#bbbbbb",
- font=self.font).pack(side="left", padx=pad)
- def _spin(self, parent, key: str, value, lo, hi, inc, width: int, fmt: str):
- tk = self.tk
- var = tk.StringVar(value=(fmt % value) if isinstance(value, (int, float))
- else str(value))
- self.vars[key] = var
- s = tk.Spinbox(parent, from_=lo, to=hi, increment=inc, width=width,
- textvariable=var, format=fmt, bg="#2a2a2a", fg="#ffffff",
- insertbackground="#ffffff", buttonbackground="#3a3a3a",
- relief="flat", font=self.font, justify="center",
- highlightthickness=0)
- s.pack(side="left")
- return s
- def _num(self, key: str, lo: float, hi: float, default: float,
- as_int: bool = False):
- try:
- value = float(str(self.vars[key].get()).strip())
- except Exception:
- value = default
- value = max(lo, min(hi, value))
- return int(round(value)) if as_int else round(value, 2)
- # ---- 按钮
- def _restore(self) -> None:
- d = DEFAULT_CONFIG
- alert, hp, exp = d["alert"], d["hp_alert"], d["exp"]
- values = {
- "alert_sound": alert["sound"], "alert_sound_seconds": alert["sound_seconds"],
- "alert_volume": alert["volume"], "alert_popup": alert["popup"],
- "alert_popup_seconds": alert["popup_seconds"],
- "bring_to_front": alert["bring_to_front"],
- "save_snapshot": alert["save_snapshot"], "threshold": d["threshold"],
- "min_hits": d["min_hits"], "max_fps": d["max_fps"],
- "confirm_frames": d.get("confirm_frames", 2),
- "require_layout": d.get("require_layout", True),
- "auto_scale": True, "scale_value": 1.0,
- "hp_enabled": hp["enabled"], "hp_low": hp["low_pct"],
- "hp_recover": hp["recover_pct"], "mp_enabled": hp["mp_enabled"],
- "mp_low": hp["mp_low_pct"], "mp_recover": hp["mp_recover_pct"],
- "hp_repeat": hp["repeat_seconds"], "hp_sound": hp["sound"],
- "hp_volume": hp["volume"], "exp_enabled": exp["enabled"],
- "exp_window": exp["window"], "exp_sample": exp["sample_seconds"],
- "aim_enabled": d.get("aim_assist", {}).get("enabled", True),
- "aim_duration": d.get("aim_assist", {}).get("duration_seconds", 25),
- "aim_on_manual": False, "aim_overlay": False,
- }
- for key, value in values.items():
- var = self.vars.get(key)
- if var is None:
- continue
- if isinstance(var, self.tk.BooleanVar):
- var.set(bool(value))
- else:
- var.set(str(value) if isinstance(value, int) else "%.2f" % value)
- log("设置已恢复成默认值(还没保存)")
- def _save(self) -> None:
- cfg = self.cfg
- alert = cfg.setdefault("alert", {})
- alert["sound"] = bool(self.vars["alert_sound"].get())
- alert["sound_seconds"] = self._num("alert_sound_seconds", 3, 120, 10, True)
- alert["volume"] = self._num("alert_volume", 0.1, 1.0, 0.9)
- alert["popup"] = bool(self.vars["alert_popup"].get())
- alert["popup_seconds"] = self._num("alert_popup_seconds", 3, 120, 12, True)
- alert["bring_to_front"] = bool(self.vars["bring_to_front"].get())
- alert["save_snapshot"] = bool(self.vars["save_snapshot"].get())
- cfg["threshold"] = self._num("threshold", 0.5, 0.99, 0.75)
- cfg["min_hits"] = self._num("min_hits", 1, 4, 2, True)
- cfg["max_fps"] = self._num("max_fps", 1, 15, 5, True)
- cfg["confirm_frames"] = self._num("confirm_frames", 1, 5, 2, True)
- cfg["require_layout"] = bool(self.vars["require_layout"].get())
- cfg["auto_scale"] = bool(self.vars["auto_scale"].get())
- if not cfg["auto_scale"]:
- # 取消自动适应 = 只按这个固定倍率查
- cfg["scales"] = [self._num("scale_value", 0.5, 2.0, 1.0)]
- hp = cfg.setdefault("hp_alert", {})
- hp["enabled"] = bool(self.vars["hp_enabled"].get())
- hp["low_pct"] = self._num("hp_low", 1, 95, 30, True)
- hp["recover_pct"] = self._num("hp_recover", 1, 99, 35, True)
- if hp["recover_pct"] <= hp["low_pct"]:
- hp["recover_pct"] = min(99, hp["low_pct"] + 5)
- hp["mp_enabled"] = bool(self.vars["mp_enabled"].get())
- hp["mp_low_pct"] = self._num("mp_low", 1, 95, 10, True)
- hp["mp_recover_pct"] = self._num("mp_recover", 1, 99, 15, True)
- if hp["mp_recover_pct"] <= hp["mp_low_pct"]:
- hp["mp_recover_pct"] = min(99, hp["mp_low_pct"] + 5)
- hp["repeat_seconds"] = self._num("hp_repeat", 5, 300, 30, True)
- hp["sound"] = bool(self.vars["hp_sound"].get())
- hp["volume"] = self._num("hp_volume", 0.1, 1.0, 0.45)
- exp = cfg.setdefault("exp", {})
- exp["enabled"] = bool(self.vars["exp_enabled"].get())
- exp["window"] = bool(self.vars["exp_window"].get())
- exp["sample_seconds"] = self._num("exp_sample", 5, 120, 10, True)
- aim = cfg.setdefault("aim_assist", {})
- aim["enabled"] = bool(self.vars["aim_enabled"].get())
- aim["duration_seconds"] = self._num("aim_duration", 5, 120, 25, True)
- aim["on_manual_test"] = bool(self.vars["aim_on_manual"].get())
- aim["show_overlay"] = bool(self.vars["aim_overlay"].get())
- self.ctl.apply_config()
- self._close()
- def _close(self) -> None:
- try:
- self.top.grab_release()
- except Exception:
- pass
- try:
- self.top.destroy()
- except Exception:
- pass
- if getattr(self.ctl, "app", None) is not None:
- self.ctl.app.settings = None
- # ---------------------------------------------------------------- 控制器
- class Controller:
- def __init__(self, cfg: dict, args):
- self.cfg = cfg
- self.args = args
- self.app = None # StatusApp,设置页要用它找主窗口
- self.events: "queue.Queue" = queue.Queue()
- self.stats = Stats()
- self.store = TemplateStore(TEMPLATE_DIR)
- self.alerter = Alerter(cfg, popup_sink=self._sink,
- quiet=bool(getattr(args, "silent", False)))
- self.hud_alert = HudAlert(cfg, popup_sink=self._toast,
- quiet=bool(getattr(args, "silent", False)))
- self.aim = None
- self.watcher = Watcher(cfg, self.store, self.alerter, self.stats,
- region_override=getattr(args, "region", None),
- hud_alert=self.hud_alert, aim=None)
- self._init_aim()
- def _init_aim(self) -> None:
- """把 ch/ 里的 YOLO+ByteTrack + Interception 瞄准挂上来。"""
- aim_cfg = dict(self.cfg.get("aim_assist") or {})
- if not aim_cfg.get("enabled", True):
- log("瞄准辅助:已关闭(config aim_assist.enabled=false)")
- return
- # exe:优先用解压目录里的 ch;源码:用项目旁的 ch/
- candidates = []
- if getattr(sys, "frozen", False):
- candidates.append(BUNDLE_DIR / "ch")
- candidates.append(APP_DIR / "ch")
- ch_dir = next((p for p in candidates if p.is_dir()), None)
- if ch_dir is None:
- log("瞄准辅助:缺少 ch/ 目录,跳过")
- return
- # 权重:exe 旁可替换的一份优先,否则用包内
- wcfg = aim_cfg.get("weights") or "models/best.pt"
- wpath = Path(wcfg)
- if not wpath.is_absolute():
- for base in (APP_DIR / "ch", ch_dir):
- cand = base / wcfg
- if cand.exists():
- wpath = cand
- break
- else:
- wpath = ch_dir / wcfg
- aim_cfg["weights"] = str(wpath)
- try:
- if str(ch_dir) not in sys.path:
- sys.path.insert(0, str(ch_dir))
- from tracker.aim_session import AimAssistController
- self.aim = AimAssistController(
- aim_cfg, region_fn=self.watcher.aim_region, log=log
- )
- self.watcher.aim = self.aim
- log("瞄准辅助:就绪(%s · %s)" % (aim_cfg.get("backend", "bytetrack"), wpath.name))
- except Exception as exc:
- self.aim = None
- log("瞄准辅助:加载失败(%s)" % exc)
- def _sink(self, info: dict) -> None:
- self.events.put(("alert", info))
- def _toast(self, info: dict) -> None:
- self.events.put(("toast", info))
- def start(self) -> None:
- self.watcher.start()
- def apply_config(self) -> None:
- """设置页点保存后:写回 config.json,并让能立刻生效的部分马上生效。"""
- save_config(self.cfg)
- # 音量是烧在 wav 里的,改了就重新合成
- try:
- self.alerter._wav = ensure_alarm_wav(
- ASSET_DIR / "alarm.wav",
- float(self.cfg.get("alert", {}).get("volume", 0.9)))
- except Exception:
- pass
- try:
- ha = self.cfg.get("hp_alert", {})
- self.hud_alert._wav = (
- ensure_hp_wav(ASSET_DIR / "hp_low.wav", float(ha.get("volume", 0.45)))
- if ha.get("sound", True) else None)
- except Exception:
- pass
- # 经验统计开关
- want = bool(self.cfg.get("exp", {}).get("enabled"))
- cur = getattr(self.watcher, "exp", None)
- if want and cur is None:
- self.watcher.exp = ExpTrack(self.cfg)
- log("经验统计:已开启")
- elif not want and cur is not None:
- try:
- cur.close()
- except Exception:
- pass
- self.watcher.exp = None
- log("经验统计:已关闭")
- log("设置已保存,阈值 %.2f · 每秒 %d 次 · 连续 %d 帧 · 低血 %.0f%% · 瞄准 %s"
- % (float(self.cfg.get("threshold", 0.75)),
- int(self.cfg.get("max_fps", 5)),
- int(self.cfg.get("confirm_frames", 2)),
- float(self.cfg.get("hp_alert", {}).get("low_pct", 30)),
- "开" if self.cfg.get("aim_assist", {}).get("enabled", True) else "关"))
- # 缩放档位立刻生效
- try:
- self.watcher.apply_scale(self.cfg.get("scales") or [1.0],
- bool(self.cfg.get("auto_scale", True)))
- self.watcher.scale_from_hud = bool(self.cfg.get("scale_from_hud", True))
- self.watcher._scale_probed = False
- except Exception:
- pass
- # 瞄准开关:关→停;开→确保控制器在
- try:
- if self.cfg.get("aim_assist", {}).get("enabled", True):
- if self.aim is None:
- self._init_aim()
- elif self.aim is not None:
- self.aim.cfg = self.cfg.get("aim_assist") or {}
- else:
- if self.aim is not None:
- self.aim.stop()
- self.aim.cfg = self.cfg.get("aim_assist") or {}
- except Exception:
- pass
- # 经验统计小窗跟着开关走
- ecfg = self.cfg.get("exp", {})
- win = getattr(self.app, "exp_win", None) if self.app is not None else None
- if want and ecfg.get("window", True) and win is None and self.app is not None:
- self.app.root.after(150, self.app._open_exp_window)
- elif not want and win is not None:
- try:
- win.destroy()
- except Exception:
- pass
- self.app.exp_win = None
- def stop(self) -> None:
- self.watcher.stop()
- self.alerter.stop_sound()
- if self.aim is not None:
- try:
- self.aim.stop()
- except Exception:
- pass
- if getattr(self.watcher, "exp", None) is not None:
- self.watcher.exp.close()
- # ---------------------------------------------------------------- 各模式
- def cmd_check(paths: List[str], cfg: dict, mark: bool = False) -> int:
- store = TemplateStore(TEMPLATE_DIR)
- if not store.items:
- print("templates/ 里没有模板,先跑 learn 模式框一块")
- return 2
- matcher = build_matcher(cfg, store.items)
- wide = None
- wide_scales = list(cfg.get("scales_wide") or [])
- threshold = float(cfg["threshold"])
- min_hits = max(1, int(cfg.get("min_hits", 2)))
- strong = float(cfg.get("strong_threshold", 0.92))
- require_layout = bool(cfg.get("require_layout", True))
- pair_avg = float(cfg.get("pair_avg_threshold", 0.82))
- ok_all = True
- for path in paths:
- gray = imread_gray(path)
- if gray is None:
- print("读不到图片:%s" % path)
- ok_all = False
- continue
- hit, per = matcher.match(gray, early_exit=False, full=True)
- if hit.score < threshold and len(wide_scales) > 1:
- # 常规档位没认出来,按常见缩放再扫一遍(诊断用,慢一点没关系)
- if wide is None:
- wide = build_matcher(cfg, store.items, wide_scales)
- wh, wper = wide.match(gray, early_exit=False, full=True)
- if wh.score > hit.score:
- print("(按 x%.2f 认出来的,你的画面缩放和模板不一样)" % wh.scale)
- hit, per = wh, wper
- clustered = cluster_hits(per, threshold) if require_layout \
- else _hit_items(per, threshold)
- hits = sum(1 for _, v in clustered
- if float(v.get("score", 0.0)) >= threshold)
- print("\n== %s (%dx%d) ==" % (Path(path).name, gray.shape[1], gray.shape[0]))
- for name, info in sorted(per.items(), key=lambda kv: -kv[1]["score"]):
- print(" %-28s %.3f x%.2f 在 (%d,%d)"
- % (name, info["score"], info["scale"],
- info["rect"][0], info["rect"][1]))
- ok = is_confirmed(hit, per, threshold, min_hits, strong,
- require_layout=require_layout, pair_avg=pair_avg)
- if not ok:
- ok_all = False
- print(" 最高 %.3f (%s x%.2f),簇内 %d 个过线 -> %s"
- "(阈值 %.2f,至少 %d 个;双模板均分≥%.2f;强阈值 %.2f;布局校验 %s)"
- % (hit.score, hit.name, hit.scale, hits,
- "命中" if ok else "不命中", threshold, min_hits, pair_avg,
- strong, "开" if require_layout else "关"))
- if mark:
- out = LOG_DIR / ("marked_%s" % Path(path).name)
- LOG_DIR.mkdir(parents=True, exist_ok=True)
- if imwrite(out, annotate(gray, per, threshold, winner=hit.name)):
- print(" 已把匹配位置画出来:%s" % out)
- return 0 if ok_all else 1
- def cmd_once(cfg: dict, args) -> int:
- store = TemplateStore(TEMPLATE_DIR)
- matcher = build_matcher(cfg, store.items)
- grabber = ScreenGrabber()
- region = args.region
- if region is None:
- hwnd, rect = find_game_window(cfg["game_window_titles"])
- region = rect or virtual_screen()
- if hwnd:
- print("游戏窗口 hwnd=0x%X 客户区=%s" % (hwnd, region))
- region = clamp_region(region)
- t0 = time.perf_counter()
- gray = grabber.grab_gray(*region)
- grab_ms = (time.perf_counter() - t0) * 1000
- if gray is None:
- print("抓屏失败")
- return 2
- # 走正式监控同一条路径,测出来的耗时才是真实值
- t0 = time.perf_counter()
- hit, per = matcher.match(gray)
- match_ms = (time.perf_counter() - t0) * 1000
- print("区域 %s 抓屏 %.1fms 识别 %.1fms" % (region, grab_ms, match_ms))
- threshold = float(cfg["threshold"])
- min_hits = max(1, int(cfg.get("min_hits", 2)))
- strong = float(cfg.get("strong_threshold", 0.92))
- require_layout = bool(cfg.get("require_layout", True))
- pair_avg = float(cfg.get("pair_avg_threshold", 0.82))
- clustered = cluster_hits(per, threshold) if require_layout \
- else _hit_items(per, threshold)
- hits = sum(1 for _, v in clustered
- if float(v.get("score", 0.0)) >= threshold)
- for name, info in sorted(per.items(), key=lambda kv: -kv[1]["score"]):
- print(" %-28s %.3f x%.2f 在 (%d,%d)"
- % (name, info["score"], info["scale"],
- info["rect"][0], info["rect"][1]))
- ok = is_confirmed(hit, per, threshold, min_hits, strong,
- require_layout=require_layout, pair_avg=pair_avg)
- print("粗查 %.3f → 最终 %.3f (%s%s) 簇内 %d 个过线 -> %s"
- % (hit.coarse, hit.score, hit.name,
- " 已复核" if hit.verified else "", hits, "命中" if ok else "不命中"))
- grabber.close()
- return 0 if ok else 1
- def cmd_list() -> int:
- print("屏幕上的顶层窗口(找游戏窗口标题用):")
- for hwnd, title in iter_windows():
- try:
- _x, _y, w, h = client_rect(hwnd)
- except Exception:
- w = h = 0
- print(" 0x%08X %4dx%-4d %s" % (hwnd, w, h, title))
- return 0
- def cmd_learn(cfg: dict, args) -> int:
- delay = max(1, int(getattr(args, "delay", 3)))
- print("把游戏画面切到「谎言探测仪」这个界面,别动。")
- for i in range(delay, 0, -1):
- print(" %d 秒后截屏…" % i, end="\r", flush=True)
- time.sleep(1)
- print(" " * 30, end="\r")
- hwnd, rect = find_game_window(cfg["game_window_titles"])
- region = args.region or rect or virtual_screen()
- region = clamp_region(region)
- grabber = ScreenGrabber()
- img = grabber.grab_bgr(*region)
- grabber.close()
- if img is None or img.size == 0:
- print("抓屏失败")
- return 2
- print("截到 %s。在弹出的窗口里,按住左键框一块「有字的地方」,回车确认,c 取消。"
- % (region,))
- win = "框选:框住测谎仪窗口里的一小段文字"
- cv2.namedWindow(win, cv2.WINDOW_NORMAL)
- max_w = 1400
- if img.shape[1] > max_w:
- s = max_w / float(img.shape[1])
- cv2.resizeWindow(win, max_w, int(img.shape[0] * s))
- else:
- cv2.resizeWindow(win, img.shape[1], img.shape[0])
- x, y, w, h = cv2.selectROI(win, img, showCrosshair=True, fromCenter=False)
- cv2.destroyAllWindows()
- if w < 12 or h < 8:
- print("没框选或框得太小,已取消。")
- return 1
- crop = img[int(y):int(y) + int(h), int(x):int(x) + int(w)]
- if float(crop.std()) < 6:
- print("框到的画面几乎是纯色,认不出来。换一块有文字的地方再试。")
- return 1
- TEMPLATE_DIR.mkdir(parents=True, exist_ok=True)
- out = TEMPLATE_DIR / ("learned_%s.png" % time.strftime("%Y%m%d_%H%M%S"))
- if not imwrite(out, crop):
- print("保存失败:%s" % out)
- return 2
- print("已保存模板:%s (%dx%d)" % (out.name, crop.shape[1], crop.shape[0]))
- print("监控开着的话会自动加载,不用重启。")
- return 0
- def cmd_demo(cfg: dict, args) -> int:
- import tkinter as tk
- img_path = ASSET_DIR / "lie_detector_window.png"
- if not img_path.exists():
- print("缺少演示图:%s" % img_path)
- return 2
- root = tk.Tk()
- root.withdraw()
- photo = tk.PhotoImage(file=str(img_path))
- w, h = photo.width(), photo.height()
- gap = float(getattr(args, "gap", 8.0))
- count = int(getattr(args, "count", 1))
- show_seconds = float(getattr(args, "seconds", 12.0))
- shown = 0
- # 假窗口要出现在「程序监控的那块画面」里:有游戏就摆游戏客户区中间,没游戏就摆屏幕中间
- _hwnd, _rect = find_game_window(cfg.get("game_window_titles", []))
- def area():
- if _rect and cfg.get("capture") != "screen":
- return _rect
- return (0, 0, root.winfo_screenwidth(), root.winfo_screenheight())
- def show_one():
- nonlocal shown
- shown += 1
- ax, ay, aw, ah = area()
- top = tk.Toplevel(root)
- top.overrideredirect(True)
- top.attributes("-topmost", True)
- top.geometry("%dx%d+%d+%d" % (w, h, ax + (aw - w) // 2, ay + (ah - h) // 2))
- tk.Label(top, image=photo, borderwidth=0, highlightthickness=0).pack()
- print("已弹出假的测谎窗口(第 %d/%d 次),%d 秒后自动关闭。"
- % (shown, count, int(show_seconds)), flush=True)
- def close():
- try:
- top.destroy()
- except Exception:
- pass
- if shown < count:
- root.after(int(gap * 1000), show_one)
- else:
- root.after(500, root.destroy)
- top.after(int(show_seconds * 1000), close)
- print("演示模式:%d 秒后弹出假窗口。监控程序应该会在 1 秒内报警。" % int(gap))
- root.after(int(gap * 1000), show_one)
- root.mainloop()
- return 0
- def cmd_hud(cfg: dict, args) -> int:
- """读一次 HUD:对图片或对现在的游戏画面,看能不能认出血蓝经验。"""
- reader = HudReader()
- if not reader.ready:
- print("templates/hud 里没有字形模板")
- return 2
- if args.paths:
- path = args.paths[0]
- gray = imread_gray(path)
- if gray is None:
- print("读不到图片:%s" % path)
- return 2
- print("图片:%s (%dx%d)" % (path, gray.shape[1], gray.shape[0]))
- else:
- hwnd, rect = find_game_window(cfg.get("game_window_titles", []))
- if not hwnd:
- print("没找到游戏窗口(最小化或没开)")
- return 2
- gray = ScreenGrabber().grab_gray(*rect)
- if gray is None:
- print("抓屏失败")
- return 2
- print("游戏窗口:%dx%d @ (%d,%d)" % (rect[2], rect[3], rect[0], rect[1]))
- vals = reader.read(gray)
- for key, label in (("hp", "血量"), ("mp", "蓝量"), ("exp", "经验")):
- v = vals.get(key)
- if v is None:
- print(" %s:读不到" % label)
- elif key == "exp":
- total = (v[0] * 100.0 / v[1]) if v[1] > 0 else None
- print(" %s:%d (%.2f%%) 这级共约 %s"
- % (label, v[0], v[1], fmt_exp(total)))
- else:
- print(" %s:%d / %d (%.0f%%)"
- % (label, v[0], v[1], v[0] * 100.0 / max(1, v[1])))
- return 0 if any(vals.values()) else 1
- def cmd_watch(cfg: dict, args) -> int:
- ctl = Controller(cfg, args)
- if not ctl.store.items:
- print("templates/ 里没有模板。先放模板,或者跑 learn 模式框一块。")
- return 2
- if getattr(args, "no_gui", False):
- ctl.start()
- log("已启动(无界面)。Ctrl+C 退出。")
- try:
- while ctl.watcher.is_alive():
- time.sleep(0.3)
- except KeyboardInterrupt:
- print("\n退出中…")
- finally:
- ctl.stop()
- return 0
- app = StatusApp(ctl)
- ctl.app = app
- ctl.start()
- try:
- app.run()
- finally:
- ctl.stop()
- return 0
- # ---------------------------------------------------------------- 入口
- def load_config() -> dict:
- cfg = json.loads(json.dumps(DEFAULT_CONFIG)) # 深拷贝
- if CONFIG_PATH.exists():
- try:
- with open(CONFIG_PATH, "r", encoding="utf-8-sig") as fh:
- user = json.load(fh)
- for key, value in user.items():
- if isinstance(value, dict) and isinstance(cfg.get(key), dict):
- cfg[key].update(value) # 分段配置:用户改了哪项就覆盖哪项
- else:
- cfg[key] = value
- except Exception as exc:
- print("config.json 读不了(%s),先用默认配置。" % exc)
- return cfg
- def save_config(cfg: dict) -> None:
- try:
- with open(CONFIG_PATH, "w", encoding="utf-8") as fh:
- json.dump(cfg, fh, ensure_ascii=False, indent=2)
- except Exception:
- pass
- def parse_region(text: str) -> Tuple[int, int, int, int]:
- parts = [p for p in re.split(r"[,\sx]+", text.strip()) if p]
- if len(parts) != 4:
- raise argparse.ArgumentTypeError("区域格式:x,y,w,h")
- return tuple(int(round(float(p))) for p in parts) # type: ignore
- def build_parser() -> argparse.ArgumentParser:
- p = argparse.ArgumentParser(
- description="冒险岛 谎言探测仪 提醒工具",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="例子:\n"
- " python lie_watcher.py\n"
- " python lie_watcher.py check test.png\n"
- " python lie_watcher.py --no-gui --threshold 0.72\n")
- p.add_argument("mode", nargs="?", default="watch",
- choices=["watch", "demo", "check", "once", "learn", "list",
- "init", "hud"])
- p.add_argument("paths", nargs="*", help="check 模式要检查的图片")
- p.add_argument("--no-gui", action="store_true", help="不显示状态小窗")
- p.add_argument("--silent", action="store_true", help="不出声、不弹窗(只记日志)")
- p.add_argument("--no-sound", action="store_true", help="关掉警报音")
- p.add_argument("--no-popup", action="store_true", help="关掉红色提醒窗")
- p.add_argument("--no-focus", action="store_true", help="不要把游戏窗口切到最前")
- p.add_argument("--threshold", type=float, help="相似度阈值 0~1")
- p.add_argument("--fps", type=float, help="每秒检查次数")
- p.add_argument("--region", type=parse_region, help="固定监控区域 x,y,w,h")
- p.add_argument("--delay", type=int, default=3, help="learn 模式截屏前等待秒数")
- p.add_argument("--gap", type=float, default=8.0, help="demo 模式弹出前等待秒数")
- p.add_argument("--count", type=int, default=1, help="demo 模式弹几次")
- p.add_argument("--seconds", type=float, default=12.0, help="demo 模式每次停留秒数")
- p.add_argument("--mark", action="store_true",
- help="check 模式:把匹配到的位置画在图上,存 logs\\marked_*.png")
- return p
- def main(argv=None) -> int:
- attach_console()
- setup_console()
- enable_dpi_awareness()
- seed_bundled_data()
- args = build_parser().parse_args(argv)
- cfg = load_config()
- if args.threshold is not None:
- cfg["threshold"] = float(args.threshold)
- if args.fps is not None:
- cfg["max_fps"] = float(args.fps)
- if args.no_sound:
- cfg["alert"]["sound"] = False
- if args.no_popup:
- cfg["alert"]["popup"] = False
- if args.no_focus:
- cfg["alert"]["bring_to_front"] = False
- if args.silent:
- cfg["alert"].update({"sound": False, "voice": False, "popup": False,
- "bring_to_front": False})
- global CONFIG
- CONFIG = cfg
- TEMPLATE_DIR.mkdir(parents=True, exist_ok=True)
- ASSET_DIR.mkdir(parents=True, exist_ok=True)
- LOG_DIR.mkdir(parents=True, exist_ok=True)
- if not CONFIG_PATH.exists():
- save_config(cfg)
- print("已生成默认配置:%s" % CONFIG_PATH)
- mode = args.mode
- if mode == "check":
- if not args.paths:
- print("check 需要图片路径,例如:python lie_watcher.py check shot.png")
- return 2
- return cmd_check(args.paths, cfg, mark=args.mark)
- if mode == "once":
- return cmd_once(cfg, args)
- if mode == "list":
- return cmd_list()
- if mode == "hud":
- return cmd_hud(cfg, args)
- if mode == "learn":
- return cmd_learn(cfg, args)
- if mode == "demo":
- return cmd_demo(cfg, args)
- if mode == "init":
- print("配置已生成:%s" % CONFIG_PATH)
- print("模板目录:%s" % TEMPLATE_DIR)
- return 0
- return cmd_watch(cfg, args)
- if __name__ == "__main__":
- try:
- sys.exit(main())
- except KeyboardInterrupt:
- print("\n已退出")
- sys.exit(0)
|