yysscript/integrated_task_tool.py

1684 lines
70 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import cv2
import numpy as np
import pyautogui
import time
import mss
import mss.tools
import os
import sys
import json
import logging
import random
from datetime import datetime
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QLabel, QLineEdit,
QPushButton, QVBoxLayout, QHBoxLayout, QTextEdit,
QFileDialog, QDoubleSpinBox, QMessageBox, QSpinBox, QCheckBox,
QGroupBox, QProgressBar, QComboBox, QTabWidget, QInputDialog,
QScrollArea
)
from PyQt5.QtCore import (
Qt, QThread, pyqtSignal, QTimer, QMutex, QMutexLocker,
QCoreApplication
)
from PyQt5.QtGui import QColor, QFont, QPainter, QPixmap
os.environ["QT_MAC_WANTS_LAYER"] = "1"
os.environ["QT_IM_MODULE"] = ""
CONFIG_FILE = "task_config.json"
LOG_FILE = "task_execution.log"
class QTextEditLogger(logging.Handler):
def __init__(self, text_edit):
super().__init__()
self.text_edit = text_edit
self.text_edit.setReadOnly(True)
def emit(self, record):
msg = self.format(record)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_msg = f"[{timestamp}] [{record.levelname}] {msg}\n"
QCoreApplication.processEvents()
if record.levelno == logging.ERROR:
self.text_edit.setTextColor(QColor(255, 0, 0))
elif record.levelno == logging.WARNING:
self.text_edit.setTextColor(QColor(255, 165, 0))
elif record.levelno == logging.SUCCESS:
self.text_edit.setTextColor(QColor(0, 128, 0))
else:
self.text_edit.setTextColor(QColor(0, 0, 0))
self.text_edit.insertPlainText(log_msg)
self.text_edit.moveCursor(self.text_edit.textCursor().End)
logging.SUCCESS = 25
logging.addLevelName(logging.SUCCESS, 'SUCCESS')
def get_random_offset(pos, max_offset=15):
x, y = pos
x_offset = random.randint(-max_offset, max_offset)
y_offset = random.randint(-max_offset, max_offset)
x_new = max(0, x + x_offset)
y_new = max(0, y + y_offset)
return (x_new, y_new), (x_offset, y_offset)
def get_random_wait(base_time, variance=0.3):
offset = base_time * variance
return base_time + random.uniform(-offset, offset)
class ScreenCapture:
def __init__(self, monitor_config=None):
self.sct = mss.MSS()
if monitor_config:
self.monitor = monitor_config
else:
self.monitor = {
"top": 240,
"left": 450,
"width": 1490,
"height": 1000
}
def capture(self):
screenshot = self.sct.grab(self.monitor)
img = np.array(screenshot)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
def capture_as_bgr(self):
screenshot = self.sct.grab(self.monitor)
img = np.array(screenshot)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
return img
def get_monitor(self):
return self.monitor
def get_full_monitor(self):
return {
"left": self.monitor['left'],
"top": self.monitor['top'],
"width": self.monitor['width'],
"height": self.monitor['height']
}
class TaskStatistics:
def __init__(self):
self.reset()
def reset(self):
self.start_time = None
self.end_time = None
self.total_cycles = 0
self.successful_cycles = 0
self.failed_cycles = 0
self.images_found = 0
self.images_not_found = 0
self.total_clicks = 0
def start(self):
self.start_time = datetime.now()
def end(self):
self.end_time = datetime.now()
def get_duration(self):
if self.start_time and self.end_time:
return (self.end_time - self.start_time).total_seconds()
return 0
def to_dict(self):
return {
"start_time": self.start_time.strftime("%Y-%m-%d %H:%M:%S") if self.start_time else None,
"end_time": self.end_time.strftime("%Y-%m-%d %H:%M:%S") if self.end_time else None,
"duration_seconds": self.get_duration(),
"total_cycles": self.total_cycles,
"successful_cycles": self.successful_cycles,
"failed_cycles": self.failed_cycles,
"images_found": self.images_found,
"images_not_found": self.images_not_found,
"total_clicks": self.total_clicks
}
class SafeTaskThread(QThread):
log_signal = pyqtSignal(str, int)
progress_signal = pyqtSignal(int)
finish_signal = pyqtSignal()
stats_signal = pyqtSignal(dict)
def __init__(self, task_type, screenshot_path, target_path, target_path2, threshold,
is_cycle, cycle_times, wait_time, max_offset=15, screen_capture=None,
jg_wait_time=15, task_images=None, interval=2, max_fail=0):
super().__init__()
self.mutex = QMutex()
self.is_running = True
self.is_paused = False
self.task_type = task_type
self.screenshot_path = screenshot_path
self.target_path = target_path
self.target_path2 = target_path2
self.threshold = threshold
self.is_cycle = is_cycle
self.cycle_times = cycle_times
self.wait_time = wait_time
self.max_offset = max_offset
self.screen_capture = screen_capture
self.jg_wait_time = jg_wait_time
self.task_images = task_images or []
self.interval = interval
self.max_fail = max_fail
self.stats = TaskStatistics()
def stop(self):
locker = QMutexLocker(self.mutex)
self.is_running = False
locker.unlock()
self.log_signal.emit("正在停止任务,请等待...", logging.WARNING)
self.wait(5000)
def pause(self):
locker = QMutexLocker(self.mutex)
self.is_paused = True
locker.unlock()
self.log_signal.emit("任务已暂停", logging.INFO)
def resume(self):
locker = QMutexLocker(self.mutex)
self.is_paused = False
locker.unlock()
self.log_signal.emit("任务已恢复", logging.INFO)
def is_thread_running(self):
locker = QMutexLocker(self.mutex)
return self.is_running
def run(self):
self.stats.start()
try:
if self.task_type == "cycle_click":
self.log_signal.emit("开始执行循环点击任务(带随机偏移)", logging.INFO)
self._run_cycle_task()
elif self.task_type == "screenshot":
self.log_signal.emit("开始执行:仅截图", logging.INFO)
self._run_screenshot_task()
elif self.task_type == "find":
self.log_signal.emit("开始执行:仅找图", logging.INFO)
self._run_find_task()
elif self.task_type == "sequence":
self.log_signal.emit("开始执行序列任务", logging.INFO)
self._run_sequence_task()
elif self.task_type == "kun28":
self.log_signal.emit("开始执行困28任务", logging.INFO)
self._run_kun28_task()
elif self.task_type == "monitor_click":
self.log_signal.emit("开始执行实时监控点击任务", logging.INFO)
self._run_monitor_click_task()
except Exception as e:
self.log_signal.emit(f"任务异常:{str(e)}", logging.ERROR)
finally:
self.stats.end()
locker = QMutexLocker(self.mutex)
self.is_running = False
self.is_paused = False
locker.unlock()
self.log_signal.emit("任务线程已安全退出", logging.INFO)
self.stats_signal.emit(self.stats.to_dict())
self.finish_signal.emit()
def _check_stop(self):
locker = QMutexLocker(self.mutex)
should_stop = not self.is_running
locker.unlock()
return should_stop
def _check_pause(self):
while True:
locker = QMutexLocker(self.mutex)
is_paused = self.is_paused
locker.unlock()
if not is_paused:
break
time.sleep(0.1)
def _capture_screen(self):
if self.screen_capture:
return self.screen_capture.capture_as_bgr()
else:
with mss.MSS() as sct:
monitor = sct.monitors[0]
screenshot = sct.grab(monitor)
img = np.array(screenshot)
return cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
def _find_image_in_screenshot(self, image_path, screenshot):
try:
if not os.path.exists(image_path):
self.log_signal.emit(f"目标图文件不存在:{image_path}", logging.ERROR)
return None
target = cv2.imread(image_path)
if target is None:
self.log_signal.emit(f"目标图读取失败:{image_path}", logging.ERROR)
return None
result = cv2.matchTemplate(screenshot, target, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
self.log_signal.emit(f"匹配度:{max_val:.4f}(阈值:{self.threshold})", logging.INFO)
if max_val >= self.threshold:
target_h, target_w = target.shape[:2]
center_x = max_loc[0] + target_w // 2
center_y = max_loc[1] + target_h // 2
target_pos = (int(center_x), int(center_y))
self.log_signal.emit(f"找到目标!坐标:{target_pos},匹配度:{max_val:.4f}", logging.SUCCESS)
self.stats.images_found += 1
return target_pos
else:
self.log_signal.emit(f"未找到目标:匹配度({max_val:.4f}) < 阈值({self.threshold})", logging.WARNING)
self.stats.images_not_found += 1
return None
except Exception as e:
self.log_signal.emit(f"找图异常:{str(e)}", logging.ERROR)
return None
def _wait_for_image(self, image_path, timeout=10, click_offset=None):
found = False
found_pos = None
start_time = time.time()
while time.time() - start_time < timeout and self.is_running and not found:
self._check_pause()
if self._check_stop():
break
screenshot = self._capture_screen()
if screenshot is not None:
pos = self._find_image_in_screenshot(image_path, screenshot)
if pos:
if click_offset:
screen_x = pos[0] + self.screen_capture.get_monitor()['left'] + click_offset[0]
screen_y = pos[1] + self.screen_capture.get_monitor()['top'] + click_offset[1]
else:
screen_x = pos[0] + self.screen_capture.get_monitor()['left']
screen_y = pos[1] + self.screen_capture.get_monitor()['top']
self._click_position(screen_x, screen_y)
found_pos = (screen_x, screen_y)
found = True
time.sleep(0.5)
return found, found_pos
def _click_position(self, x, y):
if self._check_stop():
return
try:
click_pos, offset = get_random_offset((x, y), self.max_offset)
self.log_signal.emit(f"点击坐标:原始={x,y},偏移={offset},最终={click_pos}", logging.INFO)
pyautogui.moveTo(click_pos[0], click_pos[1], duration=random.uniform(0.1, 0.3))
pyautogui.click(click_pos[0], click_pos[1])
self.log_signal.emit(f"点击完成:{click_pos}", logging.SUCCESS)
self.stats.total_clicks += 1
except Exception as e:
self.log_signal.emit(f"点击失败:{str(e)}", logging.ERROR)
def _run_full_task(self):
if self._check_stop():
return
screenshot = self._capture_screen()
if screenshot is None or self._check_stop():
return
target_pos = self._find_image_in_screenshot(self.target_path, screenshot)
if target_pos and not self._check_stop():
monitor = self.screen_capture.get_monitor()
self._click_position(target_pos[0] + monitor['left'], target_pos[1] + monitor['top'])
self.stats.successful_cycles += 1
self.log_signal.emit("一键任务执行完毕", logging.SUCCESS)
def _run_cycle_task(self):
screenshot = self._capture_screen()
if screenshot is None or self._check_stop():
return
target_pos = self._find_image_in_screenshot(self.target_path, screenshot)
if not target_pos or self._check_stop():
self.log_signal.emit("循环任务终止:未找到目标坐标或任务已停止", logging.ERROR)
self.stats.failed_cycles += 1
return
monitor = self.screen_capture.get_monitor()
click_x = target_pos[0] + monitor['left']
click_y = target_pos[1] + monitor['top']
self.log_signal.emit(f"开始循环点击:坐标={target_pos},最大随机偏移={self.max_offset}像素", logging.INFO)
self.log_signal.emit(f"循环配置:次数={self.cycle_times}(0=无限),间隔={self.wait_time}秒", logging.INFO)
cycle_count = 0
while True:
if self._check_stop():
self.log_signal.emit(f"循环任务已停止,共执行{cycle_count}次", logging.WARNING)
break
self._check_pause()
if self.cycle_times > 0 and cycle_count >= self.cycle_times:
self.log_signal.emit(f"循环完成:共执行{cycle_count}次", logging.SUCCESS)
break
cycle_count += 1
self.stats.total_cycles += 1
self.log_signal.emit(f"===== 循环第{cycle_count}次 =====", logging.INFO)
self._click_position(click_x, click_y)
actual_wait = get_random_wait(self.wait_time)
self.log_signal.emit(f"等待{actual_wait:.1f}秒(基础{self.wait_time}秒)", logging.INFO)
for i in range(int(actual_wait)):
if self._check_stop():
break
self._check_pause()
time.sleep(1)
if self._check_stop():
break
self.stats.successful_cycles += 1
if self.cycle_times == 0 and not self._check_stop():
self.log_signal.emit(f"无限循环中(第{cycle_count}次)", logging.INFO)
def _run_tp_js_cycle_task(self):
screenshot = self._capture_screen()
if screenshot is None or self._check_stop():
return
tp_pos = self._find_image_in_screenshot(self.target_path, screenshot)
if not tp_pos or self._check_stop():
self.log_signal.emit("tp+js循环任务终止:未找到tp目标坐标", logging.ERROR)
return
if not os.path.exists(self.target_path2):
self.log_signal.emit(f"js目标图文件不存在:{self.target_path2}", logging.ERROR)
return
monitor = self.screen_capture.get_monitor()
click_x = tp_pos[0] + monitor['left']
click_y = tp_pos[1] + monitor['top']
self.log_signal.emit(f"开始tp+js循环:tp坐标={tp_pos},最大随机偏移={self.max_offset}像素", logging.INFO)
cycle_count = 0
while True:
if self._check_stop():
self.log_signal.emit(f"tp+js循环任务已停止,共执行{cycle_count}次", logging.WARNING)
break
self._check_pause()
if self.cycle_times > 0 and cycle_count >= self.cycle_times:
self.log_signal.emit(f"tp+js循环完成:共执行{cycle_count}次", logging.SUCCESS)
break
cycle_count += 1
self.stats.total_cycles += 1
self.log_signal.emit(f"===== tp+js循环第{cycle_count}次 =====", logging.INFO)
self._click_position(click_x, click_y)
time.sleep(3)
tp_y_plus_150 = (click_x, click_y + 150)
self.log_signal.emit(f"y轴+150后点击,新坐标={tp_y_plus_150}", logging.INFO)
self._click_position(tp_y_plus_150[0], tp_y_plus_150[1])
time.sleep(2)
screenshot = self._capture_screen()
if not screenshot or self._check_stop():
return
self.log_signal.emit("查找js图标", logging.INFO)
js_pos = self._find_image_in_screenshot(self.target_path2, screenshot)
if not js_pos:
self.log_signal.emit("未找到js图标,跳过本次循环", logging.WARNING)
else:
self.log_signal.emit(f"点击js图标,坐标={js_pos}", logging.INFO)
js_click_x = js_pos[0] + monitor['left']
js_click_y = js_pos[1] + monitor['top']
self._click_position(js_click_x, js_click_y)
time.sleep(20)
if self._check_stop():
break
self.stats.successful_cycles += 1
if self.cycle_times == 0 and not self._check_stop():
self.log_signal.emit(f"无限循环中(第{cycle_count}次)", logging.INFO)
def _run_screenshot_task(self):
if not self._check_stop():
screenshot = self._capture_screen()
if screenshot is not None:
cv2.imwrite(self.screenshot_path, screenshot)
self.log_signal.emit(f"截图已保存:{self.screenshot_path}", logging.SUCCESS)
self.stats.successful_cycles += 1
self.log_signal.emit("截图任务执行完毕", logging.INFO)
def _run_find_task(self):
if not self._check_stop():
screenshot = self._capture_screen()
if screenshot is not None and not self._check_stop():
pos = self._find_image_in_screenshot(self.target_path, screenshot)
if pos:
monitor = self.screen_capture.get_monitor()
screen_x = pos[0] + monitor['left']
screen_y = pos[1] + monitor['top']
self.log_signal.emit(f"找到目标,屏幕坐标:({screen_x}, {screen_y}),移动鼠标...", logging.SUCCESS)
pyautogui.moveTo(screen_x, screen_y, duration=random.uniform(0.2, 0.5))
self.log_signal.emit(f"鼠标已移动到目标位置", logging.SUCCESS)
else:
self.log_signal.emit("未找到目标", logging.WARNING)
self.stats.successful_cycles += 1
self.log_signal.emit("找图任务执行完毕", logging.INFO)
def _run_sequence_task(self):
if not self.task_images or len(self.task_images) == 0:
self.log_signal.emit("序列任务错误:未配置任何图片", logging.ERROR)
return
self.log_signal.emit(f"开始序列任务,共{len(self.task_images)}张图片", logging.INFO)
self.log_signal.emit(f"查找失败上限:{self.max_fail}次(0=不限制)", logging.INFO)
self.log_signal.emit("=" * 50, logging.INFO)
monitor = self.screen_capture.get_monitor()
cycle_count = 0
total_fail_count = 0
while self.is_running:
cycle_count += 1
self.stats.total_cycles += 1
if self.cycle_times > 0 and cycle_count > self.cycle_times:
self.log_signal.emit(f"已达到循环次数限制({self.cycle_times}次),任务结束", logging.SUCCESS)
break
self.log_signal.emit(f"===== 第{cycle_count}轮序列 =====", logging.INFO)
for i, image_path in enumerate(self.task_images):
self._check_pause()
if self._check_stop():
break
self.log_signal.emit(f"[步骤{i+1}/{len(self.task_images)}] 查找 {os.path.basename(image_path)}", logging.INFO)
found = False
start_time = time.time()
while not found and self.is_running:
self._check_pause()
if self._check_stop():
break
screenshot = self._capture_screen()
if screenshot is not None:
pos = self._find_image_in_screenshot(image_path, screenshot)
if pos:
screen_x = pos[0] + monitor['left']
screen_y = pos[1] + monitor['top']
self._click_position(screen_x, screen_y)
self.log_signal.emit(f"找到 {os.path.basename(image_path)} 并点击", logging.SUCCESS)
found = True
total_fail_count = 0
time.sleep(self.interval)
if not found:
total_fail_count += 1
self.stats.failed_cycles += 1
self.log_signal.emit(f"未找到 {os.path.basename(image_path)},累计失败{total_fail_count}次", logging.WARNING)
if self.max_fail > 0 and total_fail_count >= self.max_fail:
self.log_signal.emit(f"已达到查找失败上限({self.max_fail}次),任务结束", logging.ERROR)
return
if found and self.is_running:
self._check_pause()
if self._check_stop():
break
actual_wait = get_random_wait(self.wait_time)
self.log_signal.emit(f"等待{actual_wait:.1f}秒(基础{self.wait_time}秒)...", logging.INFO)
for _ in range(int(actual_wait)):
if self._check_stop():
break
self._check_pause()
time.sleep(1)
if self._check_stop():
break
self.stats.successful_cycles += 1
self.log_signal.emit("===== 一轮序列完成 =====", logging.INFO)
self.log_signal.emit("=" * 50, logging.INFO)
time.sleep(1)
def _run_kun28_task(self):
self.log_signal.emit("开始困28任务流程", logging.INFO)
self.log_signal.emit("=" * 50, logging.INFO)
monitor = self.screen_capture.get_monitor()
center_x = monitor['width'] // 2 + monitor['left']
center_y = monitor['height'] // 2 + monitor['top']
self.log_signal.emit("[初始化] 点击屏幕中间", logging.INFO)
self._click_position(center_x, center_y)
time.sleep(3)
self.log_signal.emit("[步骤2] 识别281.png", logging.INFO)
img_281_path = self.task_images.get('281', '281.png')
found_281, pos = self._wait_for_image(img_281_path, timeout=10)
if found_281:
self.log_signal.emit("找到281.png并点击", logging.SUCCESS)
time.sleep(3)
else:
self.log_signal.emit("未找到281.png,任务可能无法正常执行", logging.WARNING)
self.log_signal.emit("[步骤3] 识别ts.png", logging.INFO)
ts_path = self.task_images.get('ts', 'ts.png')
found_ts, pos = self._wait_for_image(ts_path, timeout=10)
if found_ts:
self.log_signal.emit("找到ts.png并点击", logging.SUCCESS)
time.sleep(3)
else:
self.log_signal.emit("未找到ts.png,任务可能无法正常执行", logging.WARNING)
cycle_count = 0
while self.is_running:
cycle_count += 1
self.stats.total_cycles += 1
if self.cycle_times > 0 and cycle_count > self.cycle_times:
self.log_signal.emit(f"已达到循环次数限制({self.cycle_times}次),任务结束", logging.SUCCESS)
break
self.log_signal.emit(f"循环第{cycle_count}轮" + (f" (共{self.cycle_times}轮)" if self.cycle_times > 0 else " (无限循环)"), logging.INFO)
self.log_signal.emit("-" * 30, logging.INFO)
self._check_pause()
if self._check_stop():
break
self.log_signal.emit("[步骤1] 点击屏幕中间", logging.INFO)
self._click_position(center_x, center_y)
time.sleep(3)
self._check_pause()
if self._check_stop():
break
self.log_signal.emit("[步骤4] 识别ss.png", logging.INFO)
ss_path = self.task_images.get('ss', 'ss.png')
found_ss = False
exception_count = 0
max_exceptions = 2
while not found_ss and exception_count < max_exceptions and self.is_running:
found, pos = self._wait_for_image(ss_path, timeout=10)
if found:
self.log_signal.emit("找到ss.png并点击", logging.SUCCESS)
found_ss = True
else:
exception_count += 1
if exception_count < max_exceptions:
self.log_signal.emit(f"未找到ss.png,执行异常步骤({exception_count}/{max_exceptions})", logging.WARNING)
yd_path = self.task_images.get('yd', 'yd.png')
yd_found, yd_pos = self._wait_for_image(yd_path, timeout=10, click_offset=(0, -150))
if yd_found:
self.log_signal.emit("找到yd.png并点击(y轴-150)", logging.SUCCESS)
time.sleep(3)
else:
self.log_signal.emit("未找到yd.png", logging.WARNING)
else:
self.log_signal.emit(f"步骤4未找到ss.png,已达到异常处理上限({max_exceptions}次),任务结束", logging.ERROR)
self.stats.failed_cycles += 1
self.is_running = False
break
if found_ss and self.is_running:
actual_wait = get_random_wait(self.jg_wait_time)
self.log_signal.emit(f"等待{actual_wait:.1f}秒(基础{self.jg_wait_time}秒)...", logging.INFO)
for i in range(int(actual_wait)):
if self._check_stop():
break
self._check_pause()
time.sleep(1)
if not self.is_running:
break
self.stats.successful_cycles += 1
self.log_signal.emit("任务流程循环", logging.INFO)
self.log_signal.emit("=" * 50, logging.INFO)
time.sleep(1)
def _run_monitor_click_task(self):
self.log_signal.emit("开始实时监控点击任务", logging.INFO)
self.log_signal.emit(f"监控间隔:{self.interval}秒", logging.INFO)
self.log_signal.emit(f"点击后等待:{self.jg_wait_time}秒", logging.INFO)
self.log_signal.emit(f"目标图片数量:{len(self.task_images)}", logging.INFO)
max_offset = self.max_offset
while self.is_running:
self._check_pause()
if self._check_stop():
break
screenshot = self._capture_screen()
if screenshot is None:
time.sleep(self.interval)
continue
found_pos = None
for img_path in self.task_images:
if self._check_stop():
break
pos = self._find_image_in_screenshot(img_path, screenshot)
if pos:
found_pos = pos
break
if found_pos:
monitor = self.screen_capture.get_monitor()
click_x = found_pos[0] + monitor['left']
click_y = found_pos[1] + monitor['top']
click_pos, offset = get_random_offset((click_x, click_y), max_offset)
self.log_signal.emit(f"点击坐标:原始={click_x,click_y},偏移={offset},最终={click_pos}", logging.INFO)
self._click_position(click_pos[0], click_pos[1])
actual_wait = get_random_wait(self.jg_wait_time)
self.log_signal.emit(f"找到目标并点击,等待{actual_wait:.1f}秒", logging.INFO)
for i in range(int(actual_wait)):
if self._check_stop():
break
self._check_pause()
time.sleep(1)
time.sleep(self.interval)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
random.seed(time.time())
self.current_dir = os.path.dirname(os.path.abspath(__file__)) or os.getcwd()
self.task_thread = None
self.screen_capture = ScreenCapture()
self.config = self.load_config()
self.initUI()
self.initLogging()
self.load_settings()
self.load_sequence_presets()
def load_config(self):
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"加载配置文件失败: {e}")
return {}
def save_config(self):
try:
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(self.config, f, ensure_ascii=False, indent=4)
except Exception as e:
print(f"保存配置文件失败: {e}")
def initUI(self):
self.setWindowTitle("任务自动化工具 V6.0 (优化版)")
self.setGeometry(100, 100, 1000, 850)
self.setMinimumSize(900, 800)
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
self.tabs = QTabWidget()
self.tab_basic = QWidget()
self.tab_monitor = QWidget()
self.tab_kun28 = QWidget()
self.tab_sequence = QWidget()
self.tab_config = QWidget()
self.tabs.addTab(self.tab_basic, "基础任务")
self.tabs.addTab(self.tab_monitor, "实时监控")
self.tabs.addTab(self.tab_kun28, "困28任务")
self.tabs.addTab(self.tab_sequence, "序列任务")
self.tabs.addTab(self.tab_config, "配置管理")
self.setup_basic_tab()
self.setup_monitor_tab()
self.setup_kun28_tab()
self.setup_sequence_tab()
self.setup_config_tab()
main_layout.addWidget(self.tabs)
control_group = QGroupBox("任务控制")
control_layout = QHBoxLayout(control_group)
self.start_btn = QPushButton("开始任务")
self.start_btn.clicked.connect(self.start_task)
self.pause_btn = QPushButton("暂停")
self.pause_btn.clicked.connect(self.pause_task)
self.pause_btn.setEnabled(False)
self.stop_btn = QPushButton("停止")
self.stop_btn.clicked.connect(self.stop_task)
self.stop_btn.setEnabled(False)
control_layout.addWidget(self.start_btn)
control_layout.addWidget(self.pause_btn)
control_layout.addWidget(self.stop_btn)
self.status_label = QLabel("就绪")
control_layout.addWidget(self.status_label)
control_layout.addStretch()
main_layout.addWidget(control_group)
log_group = QGroupBox("日志输出")
log_layout = QVBoxLayout(log_group)
self.log_text = QTextEdit()
self.log_text.setReadOnly(True)
log_layout.addWidget(self.log_text)
main_layout.addWidget(log_group)
stats_group = QGroupBox("执行统计")
stats_layout = QHBoxLayout(stats_group)
self.stats_label = QLabel("运行时长: 0s | 循环: 0 | 成功: 0 | 失败: 0 | 点击: 0")
stats_layout.addWidget(self.stats_label)
self.save_log_btn = QPushButton("保存日志")
self.save_log_btn.clicked.connect(self.save_log_to_file)
stats_layout.addWidget(self.save_log_btn)
main_layout.addWidget(stats_group)
def setup_basic_tab(self):
layout = QVBoxLayout(self.tab_basic)
task_group = QGroupBox("任务配置")
task_layout = QVBoxLayout(task_group)
task_type_layout = QHBoxLayout()
task_type_label = QLabel("任务类型:")
self.task_type_combo = QComboBox()
self.task_type_combo.addItem("仅截图(screenshot)", "screenshot")
self.task_type_combo.addItem("仅找图(find)", "find")
self.task_type_combo.addItem("循环点击(cycle)", "cycle_click")
self.task_type_combo.addItem("实时监控点击(monitor_click)", "monitor_click")
self.task_type_combo.currentIndexChanged.connect(self.on_task_type_changed)
task_type_layout.addWidget(task_type_label)
task_type_layout.addWidget(self.task_type_combo)
task_layout.addLayout(task_type_layout)
target_layout = QHBoxLayout()
target_label = QLabel("目标图片路径:")
self.target_edit = QLineEdit()
target_browse_btn = QPushButton("浏览")
target_browse_btn.clicked.connect(self.browse_target_path)
target_layout.addWidget(target_label)
target_layout.addWidget(self.target_edit, 1)
target_layout.addWidget(target_browse_btn)
task_layout.addLayout(target_layout)
threshold_layout = QHBoxLayout()
threshold_label = QLabel("匹配阈值:")
self.threshold_spin = QDoubleSpinBox()
self.threshold_spin.setRange(0.5, 1.0)
self.threshold_spin.setSingleStep(0.01)
self.threshold_spin.setValue(0.8)
threshold_layout.addWidget(threshold_label)
threshold_layout.addWidget(self.threshold_spin)
threshold_layout.addStretch()
task_layout.addLayout(threshold_layout)
cycle_layout = QHBoxLayout()
cycle_label = QLabel("循环次数(0=无限):")
self.cycle_spin = QSpinBox()
self.cycle_spin.setRange(0, 9999)
self.cycle_spin.setValue(0)
cycle_layout.addWidget(cycle_label)
cycle_layout.addWidget(self.cycle_spin)
cycle_layout.addWidget(QLabel("等待时间(秒):"))
self.wait_time_spin = QSpinBox()
self.wait_time_spin.setRange(1, 999)
self.wait_time_spin.setValue(15)
cycle_layout.addWidget(self.wait_time_spin)
task_layout.addLayout(cycle_layout)
offset_layout = QHBoxLayout()
offset_label = QLabel("最大随机偏移:")
self.offset_spin = QSpinBox()
self.offset_spin.setRange(0, 50)
self.offset_spin.setValue(15)
offset_layout.addWidget(offset_label)
offset_layout.addWidget(self.offset_spin)
offset_layout.addStretch()
task_layout.addLayout(offset_layout)
self.multi_image_group = QGroupBox("多目标图片配置(实时监控点击)")
multi_image_layout = QVBoxLayout(self.multi_image_group)
preset_layout = QHBoxLayout()
preset_layout.addWidget(QLabel("配置预设:"))
self.monitor_preset_combo = QComboBox()
self.monitor_preset_combo.addItem("选择预设...", "")
self.monitor_preset_combo.currentIndexChanged.connect(self.on_monitor_preset_changed)
preset_layout.addWidget(self.monitor_preset_combo)
save_preset_btn = QPushButton("保存预设")
save_preset_btn.clicked.connect(self.save_monitor_preset)
preset_layout.addWidget(save_preset_btn)
delete_preset_btn = QPushButton("删除预设")
delete_preset_btn.clicked.connect(self.delete_monitor_preset)
preset_layout.addWidget(delete_preset_btn)
preset_layout.addStretch()
multi_image_layout.addLayout(preset_layout)
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
scroll_area.setMinimumHeight(150)
scroll_content = QWidget()
self.multi_image_layout = QVBoxLayout(scroll_content)
scroll_area.setWidget(scroll_content)
multi_image_layout.addWidget(scroll_area)
add_remove_layout = QHBoxLayout()
add_img_btn = QPushButton("+ 添加图片")
add_img_btn.clicked.connect(self.add_monitor_target)
remove_img_btn = QPushButton("- 移除最后一个")
remove_img_btn.clicked.connect(self.remove_monitor_target)
add_remove_layout.addWidget(add_img_btn)
add_remove_layout.addWidget(remove_img_btn)
multi_image_layout.addLayout(add_remove_layout)
self.multi_image_targets = []
task_layout.addWidget(self.multi_image_group)
self.multi_image_group.hide()
self.monitor_interval_widget = QWidget()
self.monitor_interval_layout = QHBoxLayout(self.monitor_interval_widget)
self.monitor_interval_layout.addWidget(QLabel("监控间隔(秒):"))
self.monitor_interval_spin = QSpinBox()
self.monitor_interval_spin.setRange(1, 60)
self.monitor_interval_spin.setValue(2)
self.monitor_interval_layout.addWidget(self.monitor_interval_spin)
self.monitor_interval_layout.addWidget(QLabel("点击后等待(秒):"))
self.monitor_click_wait_spin = QSpinBox()
self.monitor_click_wait_spin.setRange(1, 999)
self.monitor_click_wait_spin.setValue(3)
self.monitor_interval_layout.addWidget(self.monitor_click_wait_spin)
self.monitor_interval_layout.addWidget(QLabel("随机偏移:"))
self.monitor_offset_spin = QSpinBox()
self.monitor_offset_spin.setRange(0, 50)
self.monitor_offset_spin.setValue(15)
self.monitor_interval_layout.addWidget(self.monitor_offset_spin)
self.monitor_interval_layout.addStretch()
task_layout.addWidget(self.monitor_interval_widget)
self.monitor_interval_widget.hide()
self.load_monitor_click_config()
layout.addWidget(task_group)
layout.addStretch()
def setup_monitor_tab(self):
layout = QVBoxLayout(self.tab_monitor)
monitor_group = QGroupBox("截图区域实时预览")
monitor_layout = QVBoxLayout(monitor_group)
monitor_values_layout = QHBoxLayout()
monitor_values_layout.addWidget(QLabel("left:"))
self.monitor_left = QSpinBox()
self.monitor_left.setRange(0, 9999)
self.monitor_left.setValue(450)
monitor_values_layout.addWidget(self.monitor_left)
monitor_values_layout.addWidget(QLabel("top:"))
self.monitor_top = QSpinBox()
self.monitor_top.setRange(0, 9999)
self.monitor_top.setValue(240)
monitor_values_layout.addWidget(self.monitor_top)
monitor_values_layout.addWidget(QLabel("width:"))
self.monitor_width = QSpinBox()
self.monitor_width.setRange(100, 9999)
self.monitor_width.setValue(1490)
monitor_values_layout.addWidget(self.monitor_width)
monitor_values_layout.addWidget(QLabel("height:"))
self.monitor_height = QSpinBox()
self.monitor_height.setRange(100, 9999)
self.monitor_height.setValue(1000)
monitor_values_layout.addWidget(self.monitor_height)
monitor_layout.addLayout(monitor_values_layout)
preview_btn_layout = QHBoxLayout()
self.preview_toggle_btn = QPushButton("开始实时预览")
self.preview_toggle_btn.clicked.connect(self.toggle_live_preview)
preview_btn_layout.addWidget(self.preview_toggle_btn)
monitor_layout.addLayout(preview_btn_layout)
self.preview_label = QLabel('点击"开始实时预览"显示实时画面')
self.preview_label.setAlignment(Qt.AlignCenter)
self.preview_label.setStyleSheet("border: 1px solid gray; background: #2b2b2b; color: white;")
self.preview_label.setMinimumHeight(300)
monitor_layout.addWidget(self.preview_label)
self.preview_timer = None
self.is_preview_running = False
layout.addWidget(monitor_group)
layout.addStretch()
def toggle_live_preview(self):
if self.is_preview_running:
self.is_preview_running = False
if self.preview_timer:
self.preview_timer.stop()
self.preview_timer = None
self.preview_toggle_btn.setText("开始实时预览")
self.preview_label.setText('点击"开始实时预览"显示实时画面')
self.preview_label.clear()
else:
self.is_preview_running = True
self.preview_toggle_btn.setText("停止实时预览")
self.preview_timer = QTimer(self)
self.preview_timer.timeout.connect(self.update_live_preview)
self.preview_timer.start(100)
def update_live_preview(self):
try:
left = self.monitor_left.value()
top = self.monitor_top.value()
width = self.monitor_width.value()
height = self.monitor_height.value()
monitor_config = {
"left": left,
"top": top,
"width": width,
"height": height
}
sct = mss.MSS()
screenshot = sct.grab(monitor_config)
img = np.array(screenshot)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
target_path = self.target_edit.text().strip()
if target_path and os.path.exists(target_path):
try:
target = cv2.imread(target_path)
if target is not None:
result = cv2.matchTemplate(img, target, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
threshold = self.threshold_spin.value()
if max_val >= threshold:
target_h, target_w = target.shape[:2]
top_left = max_loc
bottom_right = (top_left[0] + target_w, top_left[1] + target_h)
cv2.rectangle(img, top_left, bottom_right, (0, 255, 255), 2)
center_x = top_left[0] + target_w // 2
center_y = top_left[1] + target_h // 2
cv2.putText(img, f"{max_val:.2f}", (top_left[0], top_left[1] - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
except Exception:
pass
preview_path = os.path.join(self.current_dir, "preview_region.png")
cv2.imwrite(preview_path, img)
pixmap = QPixmap(preview_path)
scaled_pixmap = pixmap.scaled(400, 300, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.preview_label.setPixmap(scaled_pixmap)
except Exception:
pass
def setup_kun28_tab(self):
layout = QVBoxLayout(self.tab_kun28)
info_label = QLabel("困28任务流程:点击中心 → 281.png → ts.png → 循环(点击中心 → ss.png[异常yd.png] → 等待)")
info_label.setStyleSheet("color: blue; font-weight: bold;")
info_label.setWordWrap(True)
layout.addWidget(info_label)
config_group = QGroupBox("困28任务图片配置")
config_layout = QVBoxLayout(config_group)
img281_layout = QHBoxLayout()
img281_layout.addWidget(QLabel("281.png 路径:"))
self.kun28_281_edit = QLineEdit()
self.kun28_281_edit.setPlaceholderText("默认为当前目录的281.png")
img281_browse_btn = QPushButton("浏览")
img281_browse_btn.clicked.connect(lambda: self.browse_image_file(self.kun28_281_edit))
img281_layout.addWidget(self.kun28_281_edit)
img281_layout.addWidget(img281_browse_btn)
config_layout.addLayout(img281_layout)
ts_layout = QHBoxLayout()
ts_layout.addWidget(QLabel("ts.png 路径:"))
self.kun28_ts_edit = QLineEdit()
self.kun28_ts_edit.setPlaceholderText("默认为当前目录的ts.png")
ts_browse_btn = QPushButton("浏览")
ts_browse_btn.clicked.connect(lambda: self.browse_image_file(self.kun28_ts_edit))
ts_layout.addWidget(self.kun28_ts_edit)
ts_layout.addWidget(ts_browse_btn)
config_layout.addLayout(ts_layout)
ss_layout = QHBoxLayout()
ss_layout.addWidget(QLabel("ss.png 路径:"))
self.kun28_ss_edit = QLineEdit()
self.kun28_ss_edit.setPlaceholderText("默认为当前目录的ss.png")
ss_browse_btn = QPushButton("浏览")
ss_browse_btn.clicked.connect(lambda: self.browse_image_file(self.kun28_ss_edit))
ss_layout.addWidget(self.kun28_ss_edit)
ss_layout.addWidget(ss_browse_btn)
config_layout.addLayout(ss_layout)
yd_layout = QHBoxLayout()
yd_layout.addWidget(QLabel("yd.png 路径:"))
self.kun28_yd_edit = QLineEdit()
self.kun28_yd_edit.setPlaceholderText("默认为当前目录的yd.png")
yd_browse_btn = QPushButton("浏览")
yd_browse_btn.clicked.connect(lambda: self.browse_image_file(self.kun28_yd_edit))
yd_layout.addWidget(self.kun28_yd_edit)
yd_layout.addWidget(yd_browse_btn)
config_layout.addLayout(yd_layout)
layout.addWidget(config_group)
task_group = QGroupBox("困28任务参数")
task_layout = QVBoxLayout(task_group)
cycle_layout = QHBoxLayout()
cycle_layout.addWidget(QLabel("循环次数(0=无限):"))
self.kun28_cycle_spin = QSpinBox()
self.kun28_cycle_spin.setRange(0, 9999)
self.kun28_cycle_spin.setValue(0)
cycle_layout.addWidget(self.kun28_cycle_spin)
cycle_layout.addWidget(QLabel("ss等待时间(秒):"))
self.kun28_wait_spin = QSpinBox()
self.kun28_wait_spin.setRange(1, 999)
self.kun28_wait_spin.setValue(15)
cycle_layout.addWidget(self.kun28_wait_spin)
cycle_layout.addStretch()
task_layout.addLayout(cycle_layout)
threshold_layout = QHBoxLayout()
threshold_layout.addWidget(QLabel("匹配阈值:"))
self.kun28_threshold_spin = QDoubleSpinBox()
self.kun28_threshold_spin.setRange(0.5, 1.0)
self.kun28_threshold_spin.setSingleStep(0.01)
self.kun28_threshold_spin.setValue(0.8)
threshold_layout.addWidget(self.kun28_threshold_spin)
threshold_layout.addWidget(QLabel("最大随机偏移:"))
self.kun28_offset_spin = QSpinBox()
self.kun28_offset_spin.setRange(0, 50)
self.kun28_offset_spin.setValue(15)
threshold_layout.addWidget(self.kun28_offset_spin)
threshold_layout.addStretch()
task_layout.addLayout(threshold_layout)
layout.addWidget(task_group)
layout.addStretch()
def setup_sequence_tab(self):
layout = QVBoxLayout(self.tab_sequence)
info_label = QLabel("序列任务:按顺序查找多张图片,找到后点击,然后继续下一张,完成后循环")
info_label.setStyleSheet("color: blue; font-weight: bold;")
info_label.setWordWrap(True)
layout.addWidget(info_label)
preset_group = QGroupBox("预设配置")
preset_layout = QHBoxLayout(preset_group)
preset_layout.addWidget(QLabel("选择配置:"))
self.seq_preset_combo = QComboBox()
self.seq_preset_combo.currentIndexChanged.connect(self.on_seq_preset_changed)
preset_layout.addWidget(self.seq_preset_combo, 1)
save_preset_btn = QPushButton("保存当前")
save_preset_btn.clicked.connect(self.save_sequence_preset)
preset_layout.addWidget(save_preset_btn)
delete_preset_btn = QPushButton("删除")
delete_preset_btn.clicked.connect(self.delete_sequence_preset)
preset_layout.addWidget(delete_preset_btn)
layout.addWidget(preset_group)
config_group = QGroupBox("序列任务图片配置")
config_layout = QVBoxLayout(config_group)
self.sequence_images = []
self.sequence_container = QWidget()
self.sequence_layout = QVBoxLayout(self.sequence_container)
config_layout.addWidget(self.sequence_container)
add_btn_layout = QHBoxLayout()
add_image_btn = QPushButton("+ 添加图片")
add_image_btn.clicked.connect(lambda: self.add_sequence_image())
remove_image_btn = QPushButton("- 移除最后一个")
remove_image_btn.clicked.connect(lambda: self.remove_sequence_image())
add_btn_layout.addWidget(add_image_btn)
add_btn_layout.addWidget(remove_image_btn)
add_btn_layout.addStretch()
config_layout.addLayout(add_btn_layout)
layout.addWidget(config_group)
task_group = QGroupBox("序列任务参数")
task_layout = QVBoxLayout(task_group)
cycle_layout = QHBoxLayout()
cycle_layout.addWidget(QLabel("循环次数(0=无限):"))
self.seq_cycle_spin = QSpinBox()
self.seq_cycle_spin.setRange(0, 9999)
self.seq_cycle_spin.setValue(0)
cycle_layout.addWidget(self.seq_cycle_spin)
cycle_layout.addWidget(QLabel("找到后等待(秒):"))
self.seq_wait_spin = QSpinBox()
self.seq_wait_spin.setRange(1, 999)
self.seq_wait_spin.setValue(3)
cycle_layout.addWidget(self.seq_wait_spin)
cycle_layout.addWidget(QLabel("搜索间隔(秒):"))
self.seq_interval_spin = QSpinBox()
self.seq_interval_spin.setRange(1, 60)
self.seq_interval_spin.setValue(2)
cycle_layout.addWidget(self.seq_interval_spin)
cycle_layout.addWidget(QLabel("查找失败上限:"))
self.seq_max_fail_spin = QSpinBox()
self.seq_max_fail_spin.setRange(0, 999)
self.seq_max_fail_spin.setValue(0)
cycle_layout.addWidget(self.seq_max_fail_spin)
cycle_layout.addStretch()
task_layout.addLayout(cycle_layout)
threshold_layout = QHBoxLayout()
threshold_layout.addWidget(QLabel("匹配阈值:"))
self.seq_threshold_spin = QDoubleSpinBox()
self.seq_threshold_spin.setRange(0.5, 1.0)
self.seq_threshold_spin.setSingleStep(0.01)
self.seq_threshold_spin.setValue(0.8)
threshold_layout.addWidget(self.seq_threshold_spin)
threshold_layout.addWidget(QLabel("最大随机偏移:"))
self.seq_offset_spin = QSpinBox()
self.seq_offset_spin.setRange(0, 50)
self.seq_offset_spin.setValue(15)
threshold_layout.addWidget(self.seq_offset_spin)
threshold_layout.addStretch()
task_layout.addLayout(threshold_layout)
layout.addWidget(task_group)
layout.addStretch()
def add_sequence_image(self):
index = len(self.sequence_images) + 1
row_layout = QHBoxLayout()
label = QLabel(f"图片{index}:")
line_edit = QLineEdit()
line_edit.setPlaceholderText(f"选择第{index}张图片路径")
browse_btn = QPushButton("浏览")
browse_btn.clicked.connect(lambda: self.browse_image_file(line_edit))
row_layout.addWidget(label)
row_layout.addWidget(line_edit, 1)
row_layout.addWidget(browse_btn)
self.sequence_layout.addLayout(row_layout)
self.sequence_images.append(line_edit)
def setup_config_tab(self):
layout = QVBoxLayout(self.tab_config)
info_label = QLabel("配置管理:编辑 task_config.json 文件内容")
info_label.setStyleSheet("color: blue; font-weight: bold;")
layout.addWidget(info_label)
json_group = QGroupBox("JSON 配置内容")
json_layout = QVBoxLayout(json_group)
self.json_text = QTextEdit()
self.json_text.setFont(QFont("Courier New", 9))
self.json_text.setPlaceholderText("JSON 配置内容...")
json_layout.addWidget(self.json_text)
btn_layout = QHBoxLayout()
refresh_btn = QPushButton("刷新")
refresh_btn.clicked.connect(self.refresh_json_config)
save_json_btn = QPushButton("保存JSON")
save_json_btn.clicked.connect(self.save_json_config)
btn_layout.addWidget(refresh_btn)
btn_layout.addWidget(save_json_btn)
btn_layout.addStretch()
json_layout.addLayout(btn_layout)
layout.addWidget(json_group)
layout.addStretch()
self.refresh_json_config()
def refresh_json_config(self):
try:
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
content = f.read()
self.json_text.setPlainText(content)
except Exception as e:
self.logger.error(f"刷新配置失败:{str(e)}")
def save_json_config(self):
try:
content = self.json_text.toPlainText()
json.loads(content)
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
f.write(content)
self.config = json.loads(content)
self.logger.info("JSON 配置已保存并重新加载")
except json.JSONDecodeError as e:
self.logger.error(f"JSON 格式错误:{str(e)}")
except Exception as e:
self.logger.error(f"保存配置失败:{str(e)}")
def remove_sequence_image(self):
if self.sequence_images:
last_layout = self.sequence_layout.itemAt(self.sequence_layout.count() - 1)
if last_layout:
while last_layout.count():
item = last_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
elif item.layout():
item.layout().deleteLater()
self.sequence_layout.removeItem(last_layout)
self.sequence_images.pop()
def get_sequence_current_config(self):
images = [edit.text() for edit in self.sequence_images if edit.text()]
return {
'images': images,
'cycle_times': self.seq_cycle_spin.value(),
'wait_time': self.seq_wait_spin.value(),
'interval': self.seq_interval_spin.value(),
'max_fail': self.seq_max_fail_spin.value(),
'threshold': self.seq_threshold_spin.value(),
'max_offset': self.seq_offset_spin.value()
}
def load_sequence_config(self, config):
while self.sequence_images:
self.remove_sequence_image()
for img_path in config.get('images', []):
self.add_sequence_image()
self.sequence_images[-1].setText(img_path)
self.seq_cycle_spin.setValue(config.get('cycle_times', 0))
self.seq_wait_spin.setValue(config.get('wait_time', 3))
self.seq_interval_spin.setValue(config.get('interval', 2))
self.seq_max_fail_spin.setValue(config.get('max_fail', 0))
self.seq_threshold_spin.setValue(config.get('threshold', 0.8))
self.seq_offset_spin.setValue(config.get('max_offset', 15))
def save_sequence_preset(self):
name, ok = QInputDialog.getText(self, "保存配置", "请输入配置名称:")
if not ok or not name:
return
name = name.strip()
if not name:
self.logger.warning("配置名称不能为空")
return
if 'sequence_presets' not in self.config:
self.config['sequence_presets'] = {}
self.config['sequence_presets'][name] = self.get_sequence_current_config()
self.save_config()
self.load_sequence_presets()
self.seq_preset_combo.setCurrentText(name)
self.logger.info(f"配置 '{name}' 已保存")
def delete_sequence_preset(self):
current = self.seq_preset_combo.currentText()
if not current:
self.logger.warning("请先选择一个配置")
return
reply = QMessageBox.question(self, "确认删除", f"确定删除配置 '{current}' 吗?",
QMessageBox.Yes | QMessageBox.No)
if reply != QMessageBox.Yes:
return
if 'sequence_presets' in self.config and current in self.config['sequence_presets']:
del self.config['sequence_presets'][current]
self.save_config()
self.load_sequence_presets()
self.logger.info(f"配置 '{current}' 已删除")
def on_seq_preset_changed(self, index):
if index < 0:
return
name = self.seq_preset_combo.currentText()
if not name:
return
if 'sequence_presets' in self.config and name in self.config['sequence_presets']:
self.load_sequence_config(self.config['sequence_presets'][name])
def load_sequence_presets(self):
self.seq_preset_combo.blockSignals(True)
self.seq_preset_combo.clear()
self.seq_preset_combo.addItem("")
if 'sequence_presets' in self.config:
for name in self.config['sequence_presets']:
self.seq_preset_combo.addItem(name)
self.seq_preset_combo.blockSignals(False)
def initLogging(self):
self.logger = logging.getLogger("TaskLogger")
self.logger.setLevel(logging.INFO)
handler = QTextEditLogger(self.log_text)
handler.setFormatter(logging.Formatter('%(message)s'))
self.logger.addHandler(handler)
file_handler = logging.FileHandler(LOG_FILE, encoding='utf-8')
file_handler.setFormatter(logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S'))
self.logger.addHandler(file_handler)
def load_settings(self):
if 'target_path' in self.config:
self.target_edit.setText(self.config['target_path'])
if 'threshold' in self.config:
self.threshold_spin.setValue(self.config['threshold'])
self.kun28_281_edit.setText(self.config.get('kun28_281', ''))
self.kun28_ts_edit.setText(self.config.get('kun28_ts', ''))
self.kun28_ss_edit.setText(self.config.get('kun28_ss', ''))
self.kun28_yd_edit.setText(self.config.get('kun28_yd', ''))
def save_settings(self):
self.config['target_path'] = self.target_edit.text()
self.config['threshold'] = self.threshold_spin.value()
self.config['kun28_281'] = self.kun28_281_edit.text()
self.config['kun28_ts'] = self.kun28_ts_edit.text()
self.config['kun28_ss'] = self.kun28_ss_edit.text()
self.config['kun28_yd'] = self.kun28_yd_edit.text()
self.config['monitor_click_images'] = [edit.text() for edit in self.multi_image_targets if edit.text()]
self.config['monitor_interval'] = self.monitor_interval_spin.value()
self.config['monitor_click_wait'] = self.monitor_click_wait_spin.value()
self.config['monitor_offset'] = self.monitor_offset_spin.value()
self.save_config()
def browse_target_path(self):
path, _ = QFileDialog.getOpenFileName(self, "选择目标图片", self.current_dir, "Image Files (*.png *.jpg)")
if path:
self.target_edit.setText(path)
def browse_image_file(self, line_edit):
path, _ = QFileDialog.getOpenFileName(self, "选择图片", self.current_dir, "Image Files (*.png *.jpg)")
if path:
line_edit.setText(path)
def add_monitor_target(self):
row_layout = QHBoxLayout()
edit = QLineEdit()
edit.setPlaceholderText("选择目标图片路径...")
browse_btn = QPushButton("浏览")
browse_btn.clicked.connect(lambda: self.browse_image_file(edit))
row_layout.addWidget(edit, 1)
row_layout.addWidget(browse_btn)
self.multi_image_layout.addLayout(row_layout)
self.multi_image_targets.append(edit)
def remove_monitor_target(self):
if self.multi_image_targets:
last = self.multi_image_targets.pop()
self.multi_image_layout.removeWidget(last)
last.deleteLater()
def load_monitor_click_config(self):
images = self.config.get('monitor_click_images', [])
for img_path in images:
row_layout = QHBoxLayout()
edit = QLineEdit()
edit.setText(img_path)
browse_btn = QPushButton("浏览")
browse_btn.clicked.connect(lambda _, e=edit: self.browse_image_file(e))
row_layout.addWidget(edit, 1)
row_layout.addWidget(browse_btn)
self.multi_image_layout.addLayout(row_layout)
self.multi_image_targets.append(edit)
self.monitor_interval_spin.setValue(self.config.get('monitor_interval', 2))
self.monitor_click_wait_spin.setValue(self.config.get('monitor_click_wait', 3))
self.monitor_offset_spin.setValue(self.config.get('monitor_offset', 15))
def on_task_type_changed(self):
task_type = self.task_type_combo.currentData()
if task_type == "monitor_click":
self.multi_image_group.show()
self.monitor_interval_widget.show()
self.load_monitor_presets()
else:
self.multi_image_group.hide()
self.monitor_interval_widget.hide()
def load_monitor_presets(self):
self.monitor_preset_combo.clear()
self.monitor_preset_combo.addItem("选择预设...", "")
presets = self.config.get('monitor_presets', {})
for name in presets.keys():
self.monitor_preset_combo.addItem(name, name)
def on_monitor_preset_changed(self):
preset_name = self.monitor_preset_combo.currentData()
if preset_name:
presets = self.config.get('monitor_presets', {})
if preset_name in presets:
preset = presets[preset_name]
self.clear_monitor_targets()
for img_path in preset.get('images', []):
row_layout = QHBoxLayout()
edit = QLineEdit()
edit.setText(img_path)
browse_btn = QPushButton("浏览")
browse_btn.clicked.connect(lambda _, e=edit: self.browse_image_file(e))
row_layout.addWidget(edit, 1)
row_layout.addWidget(browse_btn)
self.multi_image_layout.addLayout(row_layout)
self.multi_image_targets.append(edit)
self.monitor_interval_spin.setValue(preset.get('interval', 2))
self.monitor_click_wait_spin.setValue(preset.get('click_wait', 3))
self.monitor_offset_spin.setValue(preset.get('offset', 15))
def clear_monitor_targets(self):
for edit in self.multi_image_targets:
self.multi_image_layout.removeWidget(edit)
edit.deleteLater()
self.multi_image_targets.clear()
def save_monitor_preset(self):
name, ok = QInputDialog.getText(self, "保存预设", "请输入预设名称:")
if ok and name.strip():
preset = {
'images': [edit.text() for edit in self.multi_image_targets if edit.text()],
'interval': self.monitor_interval_spin.value(),
'click_wait': self.monitor_click_wait_spin.value(),
'offset': self.monitor_offset_spin.value()
}
if 'monitor_presets' not in self.config:
self.config['monitor_presets'] = {}
self.config['monitor_presets'][name.strip()] = preset
self.save_config()
self.load_monitor_presets()
def delete_monitor_preset(self):
preset_name = self.monitor_preset_combo.currentData()
if preset_name:
if 'monitor_presets' in self.config and preset_name in self.config['monitor_presets']:
del self.config['monitor_presets'][preset_name]
self.save_config()
self.load_monitor_presets()
def update_monitor_config(self):
try:
if self.cfg_monitor_left.value() >= 0:
monitor_config = {
"left": self.cfg_monitor_left.value(),
"top": self.cfg_monitor_top.value(),
"width": self.cfg_monitor_width.value(),
"height": self.cfg_monitor_height.value()
}
elif 'monitor' in self.config:
monitor_config = self.config['monitor']
else:
monitor_config = {"left": 450, "top": 240, "width": 1490, "height": 1000}
except (RuntimeError, AttributeError):
if 'monitor' in self.config:
monitor_config = self.config['monitor']
else:
monitor_config = {"left": 450, "top": 240, "width": 1490, "height": 1000}
self.screen_capture = ScreenCapture(monitor_config)
def get_current_task_params(self):
current_tab = self.tabs.currentIndex()
if current_tab == 0:
task_type = self.task_type_combo.currentData()
threshold = self.threshold_spin.value()
cycle_times = self.cycle_spin.value()
wait_time = self.wait_time_spin.value()
max_offset = self.offset_spin.value()
if task_type == "monitor_click":
task_images = [edit.text() for edit in self.multi_image_targets if edit.text()]
interval = self.monitor_interval_spin.value()
wait_time = self.monitor_click_wait_spin.value()
max_offset = self.monitor_offset_spin.value()
else:
task_images = []
interval = 2
max_fail = 0
elif current_tab == 1:
task_type = "kun28"
threshold = self.kun28_threshold_spin.value()
cycle_times = self.kun28_cycle_spin.value()
wait_time = self.kun28_wait_spin.value()
max_offset = self.kun28_offset_spin.value()
task_images = {
'281': self.kun28_281_edit.text() if self.kun28_281_edit.text() else '281.png',
'ts': self.kun28_ts_edit.text() if self.kun28_ts_edit.text() else 'ts.png',
'ss': self.kun28_ss_edit.text() if self.kun28_ss_edit.text() else 'ss.png',
'yd': self.kun28_yd_edit.text() if self.kun28_yd_edit.text() else 'yd.png'
}
else:
task_type = "sequence"
threshold = self.seq_threshold_spin.value()
cycle_times = self.seq_cycle_spin.value()
wait_time = self.seq_wait_spin.value()
max_offset = self.seq_offset_spin.value()
task_images = [edit.text() for edit in self.sequence_images if edit.text()]
interval = self.seq_interval_spin.value()
max_fail = self.seq_max_fail_spin.value()
return {
'task_type': task_type,
'threshold': threshold,
'cycle_times': cycle_times,
'wait_time': wait_time,
'max_offset': max_offset,
'task_images': task_images,
'interval': interval,
'max_fail': max_fail
}
def start_task(self):
if self.task_thread and self.task_thread.isRunning():
self.logger.warning("任务已在运行")
return
self.save_settings()
self.update_monitor_config()
params = self.get_current_task_params()
self.task_thread = SafeTaskThread(
task_type=params['task_type'],
screenshot_path=self.config.get('screenshot_path', 'full_screenshot.png'),
target_path=self.target_edit.text(),
target_path2='',
threshold=params['threshold'],
is_cycle=params['cycle_times'] > 0,
cycle_times=params['cycle_times'],
wait_time=params['wait_time'],
max_offset=params['max_offset'],
screen_capture=self.screen_capture,
jg_wait_time=params['wait_time'],
task_images=params['task_images'],
interval=params.get('interval', 2),
max_fail=params.get('max_fail', 0)
)
self.task_thread.log_signal.connect(lambda msg, level: self.logger.log(level, msg))
self.task_thread.finish_signal.connect(self.on_task_finished)
self.task_thread.stats_signal.connect(self.update_stats)
self.task_thread.start()
self.start_btn.setEnabled(False)
self.stop_btn.setEnabled(True)
self.pause_btn.setEnabled(True)
self.status_label.setText("运行中")
self.logger.info("=" * 50)
self.logger.info(f"任务已启动 - 类型: {params['task_type']}")
self.logger.info("=" * 50)
def pause_task(self):
if not self.task_thread:
return
if self.pause_btn.text() == "暂停":
self.task_thread.pause()
self.pause_btn.setText("恢复")
self.status_label.setText("已暂停")
else:
self.task_thread.resume()
self.pause_btn.setText("暂停")
self.status_label.setText("运行中")
def stop_task(self):
if not self.task_thread:
return
self.task_thread.stop()
self.logger.info("正在停止任务...")
def update_stats(self, stats):
duration = int(stats.get('duration_seconds', 0))
self.stats_label.setText(
f"运行时长: {duration}s | 循环: {stats.get('total_cycles', 0)} | "
f"成功: {stats.get('successful_cycles', 0)} | 失败: {stats.get('failed_cycles', 0)} | "
f"找到图片: {stats.get('images_found', 0)} | 点击: {stats.get('total_clicks', 0)}"
)
def on_task_finished(self):
self.start_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.pause_btn.setEnabled(False)
self.pause_btn.setText("暂停")
self.status_label.setText("已完成")
self.logger.info("任务已结束")
def save_log_to_file(self):
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_path = os.path.join(self.current_dir, f"task_log_{timestamp}.txt")
with open(log_path, 'w', encoding='utf-8') as f:
f.write(self.log_text.toPlainText())
self.logger.info(f"日志已保存:{log_path}")
QMessageBox.information(self, "成功", f"日志已保存到:{log_path}")
except Exception as e:
self.logger.error(f"保存日志失败:{str(e)}")
QMessageBox.warning(self, "错误", f"保存日志失败:{str(e)}")
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()