MuMu.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. import random
  2. import subprocess
  3. import json
  4. import time
  5. import os
  6. import tkinter as tk
  7. from tkinter import ttk, scrolledtext, messagebox, filedialog
  8. import threading
  9. import configparser
  10. from datetime import datetime
  11. # 用于存储线程的列表
  12. threads = []
  13. class MuMuEmulatorManager:
  14. # 类级别的剪贴板锁,所有实例共享
  15. _clipboard_lock = threading.Lock()
  16. def __init__(self, manager_path=r"D:\MuMuPlayer\nx_main\MuMuManager.exe"):
  17. self.manager_path = manager_path
  18. if not os.path.exists(manager_path):
  19. raise FileNotFoundError(f"找不到 MuMuManager.exe: {manager_path}")
  20. def get_adb_port(self, index, log_callback=None):
  21. """实时获取指定模拟器的 ADB 端口,获取不到就一直等待直到成功"""
  22. while True:
  23. cmd = [self.manager_path, "info", "-v", str(index)]
  24. result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
  25. if result.returncode == 0:
  26. try:
  27. data = json.loads(result.stdout)
  28. adb_port = data.get('adb_port')
  29. if adb_port is not None:
  30. if log_callback:
  31. log_callback(f"✅ 模拟器 {index} ADB端口: {adb_port}")
  32. return adb_port
  33. except:
  34. pass
  35. if log_callback:
  36. log_callback(f"⏳ 模拟器 {index} 等待ADB端口...")
  37. time.sleep(3) # 等待3秒后重试
  38. def get_emulator_list(self):
  39. """获取所有模拟器列表"""
  40. cmd = [self.manager_path, "info", "-v", "all"]
  41. result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
  42. if result.returncode != 0:
  43. return []
  44. try:
  45. data = json.loads(result.stdout)
  46. emulators = []
  47. for key, value in data.items():
  48. if isinstance(value, dict):
  49. value['index'] = key
  50. emulators.append(value)
  51. return emulators
  52. except json.JSONDecodeError:
  53. return []
  54. def start_emulator(self, index):
  55. """启动指定索引的模拟器"""
  56. cmd = [self.manager_path, "control", "-v", str(index), "launch"]
  57. result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
  58. return result.returncode == 0
  59. def wait_for_emulator_ready(self, index, timeout=120, check_interval=3, log_callback=None):
  60. """等待模拟器启动完成"""
  61. start_time = time.time()
  62. while time.time() - start_time < timeout:
  63. cmd = [self.manager_path, "info", "-v", str(index)]
  64. result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
  65. if result.returncode == 0:
  66. try:
  67. data = json.loads(result.stdout)
  68. if data.get('is_android_started') == True:
  69. return True
  70. except:
  71. pass
  72. if log_callback:
  73. log_callback(f"等待模拟器 {index} 启动... ({int(time.time() - start_time)}秒)")
  74. time.sleep(check_interval)
  75. return False
  76. def stop_emulator(self, index):
  77. """关闭模拟器"""
  78. cmd = [self.manager_path, "control", "-v", str(index), "shutdown"]
  79. result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
  80. return result.returncode == 0
  81. def clear_app_data(self, index, package_name, log_callback=None):
  82. """清除指定应用的数据"""
  83. adb_port = self.get_adb_port(index)
  84. target_device = f"127.0.0.1:{adb_port}"
  85. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  86. time.sleep(1)
  87. cmd = f"adb -s {target_device} shell pm clear {package_name}"
  88. result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
  89. if "Success" in result.stdout:
  90. if log_callback:
  91. log_callback(f"✅ 模拟器 {index} 已清除 {package_name} 数据")
  92. return True
  93. else:
  94. if log_callback:
  95. log_callback(f"⚠️ 模拟器 {index} 清除数据失败: {result.stdout}")
  96. return False
  97. def install_apk(self, index, apk_path, log_callback=None):
  98. """安装APK"""
  99. if not os.path.exists(apk_path):
  100. if log_callback:
  101. log_callback(f"❌ APK文件不存在: {apk_path}")
  102. return False
  103. adb_port = self.get_adb_port(index)
  104. target_device = f"127.0.0.1:{adb_port}"
  105. # 连接ADB
  106. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  107. time.sleep(2)
  108. # 检查是否已安装
  109. check_cmd = f"adb -s {target_device} shell pm list packages | findstr \"com.dragon.read\""
  110. check_result = subprocess.run(check_cmd, shell=True, capture_output=True, text=True)
  111. if "com.dragon.read" in check_result.stdout:
  112. if log_callback:
  113. log_callback(f"✅ com.dragon.read 已安装,跳过安装步骤")
  114. return True
  115. # 安装APK
  116. if log_callback:
  117. log_callback(f"正在安装APK: {os.path.basename(apk_path)} 端口: {adb_port}...")
  118. install_cmd = f"adb -s {target_device} install -r \"{apk_path}\""
  119. result = subprocess.run(install_cmd, shell=True, capture_output=True, text=True)
  120. return "Success" in result.stdout
  121. def open_app(self, index, package_name, log_callback=None):
  122. """打开应用"""
  123. adb_port = self.get_adb_port(index)
  124. target_device = f"127.0.0.1:{adb_port}"
  125. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  126. time.sleep(1)
  127. cmd = f"adb -s {target_device} shell monkey -p {package_name} -c android.intent.category.LAUNCHER 1"
  128. result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
  129. if "Events injected" in result.stdout or result.returncode == 0:
  130. if log_callback:
  131. log_callback(f"✅ 已打开应用: {package_name}")
  132. return True
  133. return False
  134. # 替代方案:直接发送文本字符,不用剪贴板
  135. def paste_text(self, index, text, log_callback=None):
  136. adb_port = self.get_adb_port(index)
  137. target_device = f"127.0.0.1:{adb_port}"
  138. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  139. time.sleep(0.3)
  140. # 直接通过 ADB 输入文本(逐字符)
  141. # 先确保输入框获得焦点(点击一下)
  142. subprocess.run(f"adb -s {target_device} shell input tap 390 90", shell=True)
  143. time.sleep(0.5)
  144. # 使用 adb shell input text 输入(会自动处理空格和特殊字符)
  145. # 注意:需要用 %s 转义空格
  146. safe_text = text.replace(' ', '%s').replace('&', '\\&')
  147. subprocess.run(f"adb -s {target_device} shell input text '{safe_text}'", shell=True)
  148. if log_callback:
  149. log_callback(f"✅ 已输入: {text[:50]}{'...' if len(text) > 50 else ''}")
  150. return True
  151. def tap(self, index, x, y, log_callback=None):
  152. """点击坐标"""
  153. adb_port = self.get_adb_port(index)
  154. target_device = f"127.0.0.1:{adb_port}"
  155. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  156. cmd = f"adb -s {target_device} shell input tap {x} {y}"
  157. result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
  158. if result.returncode == 0:
  159. if log_callback:
  160. log_callback(f"✅ 点击坐标 ({x}, {y})")
  161. return True
  162. return False
  163. def swipe(self, index, x1, y1, x2, y2, duration_ms=300, log_callback=None):
  164. """从坐标 (x1, y1) 滑动到 (x2, y2)"""
  165. adb_port = self.get_adb_port(index)
  166. target_device = f"127.0.0.1:{adb_port}"
  167. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  168. cmd = f"adb -s {target_device} shell input swipe {x1} {y1} {x2} {y2} {duration_ms}"
  169. result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
  170. if result.returncode == 0:
  171. if log_callback:
  172. log_callback(f"✅ 滑动从 ({x1}, {y1}) 到 ({x2}, {y2}),耗时 {duration_ms}ms")
  173. return True
  174. else:
  175. if log_callback:
  176. log_callback(f"❌ 滑动失败: {result.stderr}")
  177. return False
  178. def get_screen_size(self, index, log_callback=None):
  179. """获取模拟器屏幕分辨率,返回 (width, height)"""
  180. adb_port = self.get_adb_port(index)
  181. target_device = f"127.0.0.1:{adb_port}"
  182. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  183. time.sleep(0.5)
  184. get_resolution_cmd = f"adb -s {target_device} shell wm size"
  185. result = subprocess.run(get_resolution_cmd, shell=True, capture_output=True, text=True)
  186. if result.stdout:
  187. import re
  188. match = re.search(r'(\d+)x(\d+)', result.stdout)
  189. if match:
  190. width = int(match.group(1))
  191. height = int(match.group(2))
  192. if log_callback:
  193. log_callback(f"📱 模拟器 {index} 分辨率: {width}x{height}")
  194. return width, height
  195. return None, None
  196. def check_resolution(self, index, expected_width=720, log_callback=None):
  197. """检查分辨率宽度是否符合要求,返回 True/False"""
  198. width, height = self.get_screen_size(index, log_callback)
  199. if width is None:
  200. if log_callback:
  201. log_callback(f"⚠️ 模拟器 {index} 无法获取分辨率")
  202. return False
  203. return width == expected_width
  204. def get_pixel_color(self, index, x, y, log_callback=None):
  205. """获取模拟器内指定坐标点的颜色"""
  206. adb_port = self.get_adb_port(index)
  207. target_device = f"127.0.0.1:{adb_port}"
  208. # 连接ADB并验证连接
  209. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  210. time.sleep(0.5)
  211. # 验证设备是否在线
  212. verify_cmd = f"adb -s {target_device} shell echo 1"
  213. verify_result = subprocess.run(verify_cmd, shell=True, capture_output=True, text=True)
  214. if verify_result.returncode != 0:
  215. if log_callback:
  216. log_callback(f"⚠️ 模拟器 {index} ADB 连接失败,重新连接...")
  217. subprocess.run(f"adb disconnect {target_device}", shell=True, capture_output=True)
  218. time.sleep(1)
  219. subprocess.run(f"adb connect {target_device}", shell=True, capture_output=True)
  220. time.sleep(1)
  221. try:
  222. # 获取屏幕分辨率
  223. get_resolution_cmd = f"adb -s {target_device} shell wm size"
  224. resolution_result = subprocess.run(get_resolution_cmd, shell=True, capture_output=True, text=True)
  225. if resolution_result.stdout:
  226. import re
  227. match = re.search(r'(\d+)x(\d+)', resolution_result.stdout)
  228. if match:
  229. screen_width = int(match.group(1))
  230. screen_height = int(match.group(2))
  231. else:
  232. screen_width = 720
  233. screen_height = 1280
  234. else:
  235. screen_width = 720
  236. screen_height = 1280
  237. if log_callback:
  238. log_callback(f"📱 屏幕分辨率: {screen_width}x{screen_height}")
  239. # 使用唯一的临时文件名(包含线程ID和时间戳)
  240. import threading
  241. thread_id = threading.current_thread().ident
  242. temp_local_file = f"temp_screenshot_{thread_id}_{int(time.time()*1000)}.png"
  243. # 截图并保存到本地
  244. screenshot_cmd = f"adb -s {target_device} exec-out screencap -p > {temp_local_file}"
  245. subprocess.run(screenshot_cmd, shell=True, capture_output=True, text=True)
  246. time.sleep(0.3)
  247. # 检查文件是否存在且不为空
  248. if os.path.exists(temp_local_file) and os.path.getsize(temp_local_file) > 0:
  249. try:
  250. from PIL import Image
  251. # 打开图片
  252. img = Image.open(temp_local_file)
  253. # 确保坐标在范围内
  254. width, height = img.size
  255. if x < 0 or x >= width or y < 0 or y >= height:
  256. if log_callback:
  257. log_callback(f"❌ 坐标({x},{y})超出屏幕范围 {width}x{height}")
  258. os.remove(temp_local_file)
  259. return None
  260. # 获取像素颜色
  261. pixel = img.getpixel((x, y))
  262. # 转换为十六进制颜色值
  263. if isinstance(pixel, tuple):
  264. if len(pixel) >= 3:
  265. r, g, b = pixel[0], pixel[1], pixel[2]
  266. else:
  267. r, g, b = pixel, pixel, pixel
  268. else:
  269. r = g = b = pixel
  270. color = f"#{r:02X}{g:02X}{b:02X}"
  271. # 关闭图片并清理临时文件
  272. img.close()
  273. if os.path.exists(temp_local_file):
  274. os.remove(temp_local_file)
  275. if log_callback:
  276. log_callback(f"🎨 坐标({x},{y}) 颜色: {color}")
  277. return color
  278. except ImportError:
  279. if log_callback:
  280. log_callback("❌ 请先安装PIL库: pip install Pillow")
  281. if os.path.exists(temp_local_file):
  282. os.remove(temp_local_file)
  283. return None
  284. except Exception as e:
  285. if log_callback:
  286. log_callback(f"❌ 解析图片失败: {e}")
  287. if os.path.exists(temp_local_file):
  288. try:
  289. os.remove(temp_local_file)
  290. except:
  291. pass
  292. return None
  293. else:
  294. if log_callback:
  295. log_callback("❌ 截图失败")
  296. if os.path.exists(temp_local_file):
  297. try:
  298. os.remove(temp_local_file)
  299. except:
  300. pass
  301. return None
  302. except Exception as e:
  303. if log_callback:
  304. log_callback(f"❌ 获取颜色失败: {e}")
  305. return None
  306. class MuMuAutoGUI:
  307. def __init__(self):
  308. self.root = tk.Tk()
  309. self.root.title("MuMu模拟器自动化工具")
  310. self.root.geometry("700x360")
  311. # 配置文件
  312. self.config_file = "mumu_config.ini"
  313. self.config = configparser.ConfigParser()
  314. self.load_config()
  315. # 运行状态
  316. self.is_running = False
  317. self.is_paused = False
  318. self.should_stop = False
  319. self.current_thread = None
  320. self.selected_emulators = []
  321. self.selected_emulators = []
  322. self.thread_semaphore = None # 添加信号量控制并发数
  323. self.active_threads = 0 # 记录当前活跃线程数
  324. self.threads_lock = threading.Lock() # 线程锁
  325. self.load_btn = None
  326. self.start_read_btn = None
  327. self.start_comment_btn = None
  328. self.results = {}
  329. # 创建界面
  330. self.create_widgets()
  331. # 加载保存的配置
  332. self.load_settings()
  333. def load_config(self):
  334. """加载配置文件"""
  335. if os.path.exists(self.config_file):
  336. self.config.read(self.config_file, encoding='utf-8')
  337. else:
  338. self.config['Settings'] = {
  339. 'mumu_path': r'D:\MuMuPlayer\nx_main\MuMuManager.exe',
  340. 'apk_path': 'fanqie.apk',
  341. 'package_name': 'com.dragon.read',
  342. 'search_content': '玄幻战神:开局就得到大佬的守护'
  343. }
  344. def save_config(self):
  345. """保存配置文件"""
  346. with open(self.config_file, 'w', encoding='utf-8') as f:
  347. self.config.write(f)
  348. def load_settings(self):
  349. """加载设置到界面"""
  350. self.mumu_path_var.set(self.config['Settings']['mumu_path'] if 'mumu_path' in self.config['Settings'] else '')
  351. self.apk_path_var.set(self.config['Settings']['apk_path'] if 'apk_path' in self.config['Settings'] else '')
  352. self.package_name_var.set(self.config['Settings']['package_name'] if 'package_name' in self.config['Settings'] else '')
  353. self.search_content_var.set(self.config['Settings']['search_content'] if 'search_content' in self.config['Settings'] else '盗墓笔记')
  354. self.page_count_var.set(self.config['Settings']['page_count_var'] if 'page_count_var' in self.config['Settings'] else '10-30')
  355. self.page_interval_var.set(self.config['Settings']['page_interval_var'] if 'page_interval_var' in self.config['Settings'] else '5')
  356. self.max_threads_var.set(self.config['Settings']['max_threads_var'] if 'max_threads_var' in self.config['Settings'] else '1')
  357. def save_settings(self):
  358. """保存界面设置到文件"""
  359. self.config['Settings']['mumu_path'] = self.mumu_path_var.get()
  360. self.config['Settings']['apk_path'] = self.apk_path_var.get()
  361. self.config['Settings']['package_name'] = self.package_name_var.get()
  362. self.config['Settings']['search_content'] = self.search_content_var.get()
  363. self.config['Settings']['page_count_var'] = self.page_count_var.get()
  364. self.config['Settings']['page_interval_var'] = self.page_interval_var.get()
  365. self.config['Settings']['max_threads_var'] = self.max_threads_var.get()
  366. self.save_config()
  367. self.log_message("✅ 配置已保存")
  368. def create_widgets(self):
  369. """创建界面组件"""
  370. # 创建选项卡
  371. self.notebook = ttk.Notebook(self.root)
  372. self.notebook.pack(fill='both', expand=True, padx=5, pady=5)
  373. # 配置选项卡
  374. self.create_config_tab()
  375. # 任务选项卡
  376. self.create_task_tab()
  377. # 日志选项卡
  378. self.create_log_tab()
  379. def create_config_tab(self):
  380. """创建配置选项卡"""
  381. config_frame = ttk.Frame(self.notebook)
  382. self.notebook.add(config_frame, text="配置")
  383. # 创建滚动框架
  384. canvas = tk.Canvas(config_frame)
  385. scrollbar = ttk.Scrollbar(config_frame, orient="vertical", command=canvas.yview)
  386. scrollable_frame = ttk.Frame(canvas)
  387. scrollable_frame.bind(
  388. "<Configure>",
  389. lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
  390. )
  391. canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
  392. canvas.configure(yscrollcommand=scrollbar.set)
  393. # 配置项
  394. row = 0
  395. # MuMu路径
  396. ttk.Label(scrollable_frame, text="MuMuManager路径:").grid(row=row, column=0, sticky='w', padx=10, pady=5)
  397. self.mumu_path_var = tk.StringVar()
  398. mumu_entry = ttk.Entry(scrollable_frame, textvariable=self.mumu_path_var, width=60)
  399. mumu_entry.grid(row=row, column=1, padx=10, pady=5)
  400. ttk.Button(scrollable_frame, text="浏览", command=self.browse_mumu_path).grid(row=row, column=2, padx=5, pady=5)
  401. row += 1
  402. # APK路径
  403. ttk.Label(scrollable_frame, text="APK文件路径:").grid(row=row, column=0, sticky='w', padx=10, pady=5)
  404. self.apk_path_var = tk.StringVar()
  405. apk_entry = ttk.Entry(scrollable_frame, textvariable=self.apk_path_var, width=60)
  406. apk_entry.grid(row=row, column=1, padx=10, pady=5)
  407. ttk.Button(scrollable_frame, text="浏览", command=self.browse_apk_path).grid(row=row, column=2, padx=5, pady=5)
  408. row += 1
  409. # 包名
  410. ttk.Label(scrollable_frame, text="应用包名:").grid(row=row, column=0, sticky='w', padx=10, pady=5)
  411. self.package_name_var = tk.StringVar()
  412. ttk.Entry(scrollable_frame, textvariable=self.package_name_var, width=40).grid(row=row, column=1, sticky='w', padx=10, pady=5)
  413. row += 1
  414. # 搜索内容
  415. ttk.Label(scrollable_frame, text="搜索内容:").grid(row=row, column=0, sticky='w', padx=10, pady=5)
  416. self.search_content_var = tk.StringVar()
  417. ttk.Entry(scrollable_frame, textvariable=self.search_content_var, width=60).grid(row=row, column=1, padx=10, pady=5)
  418. row += 1
  419. # 翻页间隔
  420. ttk.Label(scrollable_frame, text="翻页间隔(秒):").grid(row=row, column=0, sticky='w', padx=10, pady=5)
  421. self.page_interval_var = tk.StringVar()
  422. ttk.Entry(scrollable_frame, textvariable=self.page_interval_var, width=60).grid(row=row, column=1, padx=10, pady=5)
  423. row += 1
  424. # 阅读页数
  425. ttk.Label(scrollable_frame, text="阅读页数:").grid(row=row, column=0, sticky='w', padx=10, pady=5)
  426. self.page_count_var = tk.StringVar()
  427. ttk.Entry(scrollable_frame, textvariable=self.page_count_var, width=60).grid(row=row, column=1, padx=10, pady=5)
  428. row += 1
  429. # 最大线程
  430. ttk.Label(scrollable_frame, text="最大线程:").grid(row=row, column=0, sticky='w', padx=10, pady=5)
  431. self.max_threads_var = tk.StringVar()
  432. ttk.Entry(scrollable_frame, textvariable=self.max_threads_var, width=60).grid(row=row, column=1, padx=10, pady=5)
  433. row += 1
  434. # 保存按钮
  435. ttk.Button(scrollable_frame, text="保存配置", command=self.save_settings).grid(row=row, column=0, columnspan=3, pady=20)
  436. canvas.pack(side="left", fill="both", expand=True)
  437. scrollbar.pack(side="right", fill="y")
  438. def select_failed_emulators(self):
  439. """选择所有执行失败的模拟器"""
  440. if not self.results:
  441. self.log_message("⚠️ 没有任务执行记录,请先运行任务")
  442. return
  443. failed_indices = [idx for idx, success in self.results.items() if not success]
  444. if not failed_indices:
  445. self.log_message("✅ 没有失败的模拟器")
  446. return
  447. # 清空当前选择
  448. for item in self.emulator_tree.get_children():
  449. values = self.emulator_tree.item(item, 'values')
  450. if values[0] == "☑":
  451. self.emulator_tree.item(item, values=("□", values[1], values[2], values[3]))
  452. # 选中失败的模拟器
  453. selected_count = 0
  454. for item in self.emulator_tree.get_children():
  455. values = self.emulator_tree.item(item, 'values')
  456. if values[1] in failed_indices:
  457. self.emulator_tree.item(item, values=("☑", values[1], values[2], values[3]))
  458. selected_count += 1
  459. self.log_message(f"✅ 已选中 {selected_count} 个失败模拟器: {', '.join(failed_indices)}")
  460. def create_task_tab(self):
  461. """创建任务选项卡"""
  462. task_frame = ttk.Frame(self.notebook)
  463. self.notebook.add(task_frame, text="任务")
  464. # 上部:模拟器列表
  465. list_frame = ttk.LabelFrame(task_frame, text="任务控制")
  466. list_frame.pack(fill='both', expand=True, padx=5, pady=5)
  467. # 按钮栏
  468. button_frame = ttk.Frame(list_frame)
  469. button_frame.pack(fill='x', padx=5, pady=5)
  470. self.load_btn = ttk.Button(button_frame, text="读取模拟器", command=self.load_emulators)
  471. self.load_btn.pack(side='left', padx=5)
  472. # 添加全选按钮
  473. self.select_all_btn = ttk.Button(button_frame, text="全选", command=self.select_all_emulators, width=6)
  474. self.select_all_btn.pack(side='left', padx=5)
  475. # 添加选择失败项按钮
  476. self.select_failed_btn = ttk.Button(button_frame, text="选择失败项", command=self.select_failed_emulators, width=10)
  477. self.select_failed_btn.pack(side='left', padx=5)
  478. self.start_read_btn = ttk.Button(button_frame, text="开始阅读", command=self.start_task, width=10)
  479. self.start_read_btn.pack(side='left', padx=10)
  480. self.start_comment_btn = ttk.Button(button_frame, text="开始评价", command=self.start_task2, width=10)
  481. self.start_comment_btn.pack(side='left', padx=10)
  482. self.pause_btn = ttk.Button(button_frame, text="暂停", command=self.pause_task, width=10, state='disabled')
  483. self.pause_btn.pack(side='left', padx=10)
  484. self.stop_btn = ttk.Button(button_frame, text="停止", command=self.stop_task, width=10, state='disabled')
  485. self.stop_btn.pack(side='left', padx=10)
  486. # 模拟器列表(带复选框)
  487. tree_frame = ttk.Frame(list_frame)
  488. tree_frame.pack(fill='both', expand=True, padx=5, pady=5)
  489. # 创建Treeview
  490. columns = ("选择", "索引", "名称", "状态")
  491. self.emulator_tree = ttk.Treeview(tree_frame, columns=columns, show='headings', height=8)
  492. # 设置列标题
  493. self.emulator_tree.heading("选择", text="选择")
  494. self.emulator_tree.heading("索引", text="索引")
  495. self.emulator_tree.heading("名称", text="名称")
  496. self.emulator_tree.heading("状态", text="状态")
  497. # 设置列宽
  498. self.emulator_tree.column("选择", width=50)
  499. self.emulator_tree.column("索引", width=50)
  500. self.emulator_tree.column("名称", width=150)
  501. self.emulator_tree.column("状态", width=100)
  502. # 添加滚动条
  503. vsb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.emulator_tree.yview)
  504. self.emulator_tree.configure(yscrollcommand=vsb.set)
  505. self.emulator_tree.pack(side='left', fill='both', expand=True)
  506. vsb.pack(side='right', fill='y')
  507. # 绑定双击选择
  508. self.emulator_tree.bind('<Button-1>', self.on_tree_click)
  509. def create_log_tab(self):
  510. """创建日志选项卡"""
  511. log_frame = ttk.Frame(self.notebook)
  512. self.notebook.add(log_frame, text="日志")
  513. # 日志文本框
  514. self.log_text = scrolledtext.ScrolledText(log_frame, wrap=tk.WORD, height=20)
  515. self.log_text.pack(fill='both', expand=True, padx=5, pady=5)
  516. # 清空按钮
  517. btn_frame = ttk.Frame(log_frame)
  518. btn_frame.pack(fill='x', padx=5, pady=5)
  519. ttk.Button(btn_frame, text="清空日志", command=self.clear_log).pack(side='right')
  520. def browse_mumu_path(self):
  521. """浏览MuMuManager路径"""
  522. path = filedialog.askopenfilename(title="选择MuMuManager.exe", filetypes=[("Executable", "*.exe")])
  523. if path:
  524. self.mumu_path_var.set(path)
  525. def browse_apk_path(self):
  526. """浏览APK文件"""
  527. path = filedialog.askopenfilename(title="选择APK文件", filetypes=[("APK", "*.apk")])
  528. if path:
  529. self.apk_path_var.set(path)
  530. def select_all_emulators(self):
  531. """全选所有模拟器"""
  532. for item in self.emulator_tree.get_children():
  533. values = self.emulator_tree.item(item, 'values')
  534. if values[0] == "□":
  535. self.emulator_tree.item(item, values=("☑", values[1], values[2], values[3]))
  536. self.log_message("已全选所有模拟器")
  537. def update_emulator_status(self, index, status):
  538. """更新指定索引的模拟器状态显示
  539. Args:
  540. index: 模拟器索引(字符串)
  541. status: 状态文本,如 "运行中" 或 "未运行"
  542. """
  543. for item in self.emulator_tree.get_children():
  544. values = self.emulator_tree.item(item, 'values')
  545. if values[1] == str(index):
  546. self.emulator_tree.item(item, values=(values[0], values[1], values[2], status))
  547. break
  548. def load_emulators(self):
  549. """加载模拟器列表"""
  550. try:
  551. manager = MuMuEmulatorManager(self.mumu_path_var.get())
  552. emulators = manager.get_emulator_list()
  553. # 清空现有列表
  554. for item in self.emulator_tree.get_children():
  555. self.emulator_tree.delete(item)
  556. # 添加模拟器
  557. for emu in emulators:
  558. status = "运行中" if emu.get('is_process_started') else "未运行"
  559. self.emulator_tree.insert('', 'end', values=("□", emu.get('index'), emu.get('name'), status))
  560. self.log_message(f"已加载 {len(emulators)} 个模拟器")
  561. except Exception as e:
  562. self.log_message(f"加载模拟器失败: {e}")
  563. def on_tree_click(self, event):
  564. """处理列表点击选择"""
  565. region = self.emulator_tree.identify_region(event.x, event.y)
  566. if region == "cell":
  567. column = self.emulator_tree.identify_column(event.x)
  568. if column == "#1": # 选择列
  569. item = self.emulator_tree.identify_row(event.y)
  570. if item:
  571. values = self.emulator_tree.item(item, 'values')
  572. current = values[0]
  573. new_value = "☑" if current == "□" else "□"
  574. self.emulator_tree.item(item, values=(new_value, values[1], values[2], values[3]))
  575. def get_selected_emulators(self):
  576. """获取选中的模拟器"""
  577. selected = []
  578. for item in self.emulator_tree.get_children():
  579. values = self.emulator_tree.item(item, 'values')
  580. if values[0] == "☑":
  581. selected.append({
  582. 'index': values[1],
  583. 'name': values[2]
  584. })
  585. return selected
  586. def log_message(self, message):
  587. """添加日志"""
  588. timestamp = datetime.now().strftime("%H:%M:%S")
  589. self.log_text.insert(tk.END, f"[{timestamp}] {message}\n")
  590. self.log_text.see(tk.END)
  591. self.root.update()
  592. def start_task(self):
  593. """开始阅读任务"""
  594. selected = self.get_selected_emulators()
  595. if not selected:
  596. messagebox.showwarning("警告", "请至少选择一个模拟器")
  597. return
  598. self.selected_emulators = selected
  599. self.is_running = True
  600. self.is_paused = False
  601. self.should_stop = False
  602. # 禁用相关按钮
  603. self.load_btn.config(state='disabled')
  604. self.start_read_btn.config(state='disabled')
  605. self.start_comment_btn.config(state='disabled')
  606. self.pause_btn.config(state='normal')
  607. self.stop_btn.config(state='normal')
  608. # 在新线程中运行任务
  609. self.current_thread = threading.Thread(target=self.run_task, daemon=True)
  610. self.current_thread.start()
  611. def start_task2(self):
  612. """开始评价任务"""
  613. selected = self.get_selected_emulators()
  614. if not selected:
  615. messagebox.showwarning("警告", "请至少选择一个模拟器")
  616. return
  617. self.selected_emulators = selected
  618. self.is_running = True
  619. self.is_paused = False
  620. self.should_stop = False
  621. # 禁用相关按钮
  622. self.load_btn.config(state='disabled')
  623. self.start_read_btn.config(state='disabled')
  624. self.start_comment_btn.config(state='disabled')
  625. self.pause_btn.config(state='normal')
  626. self.stop_btn.config(state='normal')
  627. # 在新线程中运行评价任务
  628. self.current_thread = threading.Thread(target=self.run_task2, daemon=True)
  629. self.current_thread.start()
  630. def pause_task(self):
  631. """暂停任务"""
  632. if self.is_running and not self.is_paused:
  633. self.is_paused = True
  634. self.pause_btn.config(text="继续")
  635. self.log_message("⏸ 任务已暂停")
  636. elif self.is_running and self.is_paused:
  637. self.is_paused = False
  638. self.pause_btn.config(text="暂停")
  639. self.log_message("▶️ 任务已继续")
  640. def stop_task(self):
  641. """停止任务"""
  642. if self.is_running:
  643. self.should_stop = True
  644. self.is_running = False
  645. self.is_paused = False
  646. self.log_message("⏹ 正在停止任务...")
  647. def openBook(self, manager, index):
  648. """打开书籍,遇到错误返回False"""
  649. # 执行操作
  650. manager.tap(index, 390, 90, self.log_message)
  651. errNumber = 0
  652. while True:
  653. color56065 = manager.get_pixel_color(index, 560, 65, log_callback=self.log_message)
  654. if color56065 == "#F7F7F7":
  655. break
  656. elif color56065 == "#EBF8EC":
  657. manager.tap(index, 390, 90, self.log_message)
  658. self.log_message(f"模拟器 {index} 尝试重新点击搜索...")
  659. elif color56065 == "#5E635E":
  660. self.log_message(f"模拟器 {index} 需要关闭红包弹窗...")
  661. manager.tap(index, 640, 260, self.log_message)
  662. time.sleep(20)
  663. manager.tap(index, 57, 193, self.log_message)
  664. elif color56065 in ["#EBE8E4", "#CDD0D1"]:
  665. self.log_message(f"模拟器 {index} 进入错误页面,返回...")
  666. manager.tap(index, 44, 92, self.log_message)
  667. else:
  668. errNumber = errNumber + 1
  669. if errNumber > 30:
  670. self.log_message(f"模拟器 {index} 连续多次未检测到搜索页面,设置错误并退出...")
  671. manager.stop_emulator(index)
  672. return False
  673. self.log_message(f"模拟器 {index} 等待搜索页面准备就绪...")
  674. time.sleep(3)
  675. time.sleep(3)
  676. # 点输入框
  677. manager.tap(index, 340, 90, self.log_message)
  678. time.sleep(3)
  679. # 黏贴
  680. manager.paste_text(index, self.search_content_var.get(), self.log_message)
  681. time.sleep(3)
  682. errNumber = 0
  683. while True:
  684. if manager.get_pixel_color(index, 435, 880, log_callback=self.log_message) == "#FFFFFF":
  685. break
  686. errNumber = errNumber + 1
  687. if errNumber > 30:
  688. self.log_message(f"模拟器 {index} 连续多次未检测到搜索页面,设置错误并退出...")
  689. manager.stop_emulator(index)
  690. return False
  691. self.log_message(f"模拟器 {index} 没有输入搜索内容...")
  692. # 点输入框
  693. manager.tap(index, 556, 87, self.log_message)
  694. time.sleep(1)
  695. manager.tap(index, 340, 90, self.log_message)
  696. time.sleep(2)
  697. # 黏贴
  698. manager.paste_text(index, self.search_content_var.get(), self.log_message)
  699. time.sleep(3)
  700. manager.tap(index, 655, 92, self.log_message)
  701. time.sleep(6)
  702. errNumber = 0
  703. while True:
  704. color630235 = manager.get_pixel_color(index, 630, 235, log_callback=self.log_message)
  705. if color630235 in ["#FFFFFF"]:
  706. self.log_message(f"模拟器 {index} 已经在搜索结果页面,继续...")
  707. break
  708. elif color630235 in ["#E8E3CE", "#E0DBC6", "#CCCBCB", "#DFDAC5", "#141000"]:
  709. self.log_message(f"模拟器 {index} 已经在看书目录界面,继续...")
  710. break
  711. elif color630235 in ["#F9F9FC"]:
  712. self.log_message(f"模拟器 {index} 关闭广告弹窗,继续...")
  713. manager.tap(index, 634, 123, self.log_message)
  714. else:
  715. errNumber = errNumber + 1
  716. if errNumber > 30:
  717. self.log_message(f"模拟器 {index} 连续多次未检测到搜索页面,设置错误并退出...")
  718. manager.stop_emulator(index)
  719. return False
  720. self.log_message(f"模拟器 {index} 等待搜索结果...")
  721. time.sleep(3)
  722. # 进入书目
  723. time.sleep(6)
  724. manager.tap(index, 355, 333, self.log_message)
  725. time.sleep(5)
  726. errNumber = 0
  727. while True:
  728. color630235 = manager.get_pixel_color(index, 630, 235, log_callback=self.log_message)
  729. if color630235 in ["#E8E3CE", "#E0DBC6", "#CCCBCB", "#DFDAC5", "#141000", "#E3DEC9"]:
  730. self.log_message(f"模拟器 {index} 已经在看书目录界面,继续...")
  731. return True
  732. else:
  733. errNumber = errNumber + 1
  734. if errNumber > 20:
  735. self.log_message(f"模拟器 {index} 连续多次未检测到搜索页面,设置错误并退出...")
  736. manager.stop_emulator(index)
  737. return False
  738. self.log_message(f"模拟器 {index} 还在搜索结果页面,重新点击...")
  739. manager.tap(index, 355, 333, self.log_message)
  740. time.sleep(5)
  741. def run_task(self):
  742. """执行任务(支持并发,出错直接退出不重试)"""
  743. global threads
  744. try:
  745. # 获取最大线程数
  746. max_threads = int(self.max_threads_var.get()) if self.max_threads_var.get().isdigit() else 1
  747. self.thread_semaphore = threading.Semaphore(max_threads)
  748. self.active_threads = 0
  749. self.log_message(f"📌 最大并发数: {max_threads}")
  750. threads = []
  751. def process_emulator(emu):
  752. """处理单个模拟器的函数,出错直接退出"""
  753. # 获取信号量,控制并发数
  754. self.thread_semaphore.acquire()
  755. # 增加活跃线程计数
  756. with self.threads_lock:
  757. self.active_threads += 1
  758. current_active = self.active_threads
  759. self.log_message(f"📊 当前活跃线程数: {current_active}/{max_threads}")
  760. index = emu['index']
  761. try:
  762. if self.should_stop:
  763. return
  764. self.log_message(f"\n{'='*50}")
  765. self.log_message(f"开始处理模拟器 {index} ({emu['name']})")
  766. self.log_message(f"{'='*50}")
  767. # 更新状态为运行中
  768. self.root.after(0, lambda: self.update_emulator_status(index, "运行中"))
  769. manager = MuMuEmulatorManager(self.mumu_path_var.get())
  770. # 启动模拟器
  771. self.log_message(f"正在启动模拟器 {index}...")
  772. if not manager.start_emulator(index):
  773. self.log_message(f"❌ 模拟器 {index} 启动失败")
  774. self.results[index] = False
  775. self.root.after(0, lambda: self.update_emulator_status(index, "启动失败"))
  776. return
  777. # 等待就绪
  778. if not manager.wait_for_emulator_ready(index, timeout=180, log_callback=self.log_message):
  779. self.log_message(f"❌ 模拟器 {index} 启动超时")
  780. self.results[index] = False
  781. self.root.after(0, lambda: self.update_emulator_status(index, "启动超时"))
  782. return
  783. time.sleep(5)
  784. if not manager.check_resolution(index, 720, self.log_message):
  785. self.log_message(f"❌ 模拟器 {index} 分辨率不是720,停止任务并关闭模拟器")
  786. manager.stop_emulator(index)
  787. self.results[index] = False
  788. self.root.after(0, lambda: self.update_emulator_status(index, "分辨率错误"))
  789. return
  790. # 安装APK
  791. if not manager.install_apk(index, self.apk_path_var.get(), self.log_message):
  792. self.log_message(f"⚠️ APK安装失败,但继续执行...")
  793. # 打开应用
  794. manager.open_app(index, self.package_name_var.get(), self.log_message)
  795. # 判断是否需要同意
  796. time.sleep(20)
  797. button_color = manager.get_pixel_color(index, 394, 846, log_callback=self.log_message)
  798. # 是否是第一次进入
  799. if button_color and button_color.upper() == "#FC7838":
  800. manager.tap(index, 394, 846, self.log_message)
  801. time.sleep(120)
  802. manager.tap(index, 640, 260, self.log_message)
  803. time.sleep(20)
  804. manager.tap(index, 57, 193, self.log_message)
  805. time.sleep(5)
  806. else:
  807. time.sleep(10)
  808. # 等待进入主界面
  809. errNumber = 0
  810. while True:
  811. if self.should_stop or self.is_paused:
  812. # 处理暂停
  813. while self.is_paused and not self.should_stop:
  814. time.sleep(1)
  815. if self.should_stop:
  816. return
  817. color560130 = manager.get_pixel_color(index, 560, 130, log_callback=self.log_message)
  818. if color560130 in ["#EEF8EE", "#F7F7F7"]:
  819. self.log_message(f"模拟器 {index} 已经进入主界面,继续...")
  820. break
  821. elif color560130 in ["#5F635F"]:
  822. self.log_message(f"模拟器 {index} 需要关闭红包弹窗...")
  823. manager.tap(index, 640, 260, self.log_message)
  824. time.sleep(20)
  825. manager.tap(index, 57, 193, self.log_message)
  826. elif color560130 in ["#CED0D2"]:
  827. self.log_message(f"模拟器 {index} 需要关闭广告弹窗...")
  828. manager.tap(index, 200, 80, self.log_message)
  829. elif color560130 in ["#F3CEA9"]:
  830. self.log_message(f"模拟器 {index} 进入错误页面,返回...")
  831. manager.tap(index, 44, 92, self.log_message)
  832. time.sleep(20)
  833. manager.tap(index, 57, 193, self.log_message)
  834. else:
  835. errNumber = errNumber + 1
  836. if errNumber > 30:
  837. self.log_message(f"模拟器 {index} 连续多次未进入主界面,退出...")
  838. manager.stop_emulator(index)
  839. self.results[index] = False
  840. self.root.after(0, lambda: self.update_emulator_status(index, "进入主界面失败"))
  841. return
  842. self.log_message(f"模拟器 {index} 等待进入主界面中...")
  843. time.sleep(5)
  844. # 执行打开书籍
  845. if not self.openBook(manager, index):
  846. self.results[index] = False
  847. self.root.after(0, lambda: self.update_emulator_status(index, "打开书籍失败"))
  848. return
  849. time.sleep(8)
  850. # 翻页
  851. page_range = self.page_count_var.get()
  852. if '-' in page_range:
  853. parts = page_range.split('-')
  854. if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
  855. page_count = random.randint(int(parts[0]), int(parts[1]))
  856. else:
  857. page_count = 10
  858. else:
  859. page_count = int(page_range) if page_range.isdigit() else 10
  860. for page in range(page_count):
  861. if self.should_stop or self.is_paused:
  862. # 处理暂停
  863. while self.is_paused and not self.should_stop:
  864. time.sleep(1)
  865. if self.should_stop:
  866. return
  867. # 判断是否在看书目录界面
  868. errNumber = 0
  869. while True:
  870. color7001000 = manager.get_pixel_color(index, 700, 1000, log_callback=self.log_message)
  871. if color7001000 in ["#E8E3CE", "#E0DBC6", "#CCCBCB"]:
  872. self.log_message(f"模拟器 {index} 在看书目录界面,继续翻页...")
  873. break
  874. elif color7001000 in ["#F9F9FC"]:
  875. self.log_message(f"模拟器 {index} 遇到广告,点击跳过...")
  876. manager.tap(index, 700, 300, self.log_message)
  877. else:
  878. errNumber = errNumber + 1
  879. if errNumber > 10:
  880. self.log_message(f"模拟器 {index} 连续多次未检测到目录界面,退出...")
  881. manager.stop_emulator(index)
  882. self.results[index] = False
  883. self.root.after(0, lambda: self.update_emulator_status(index, "翻页失败"))
  884. return
  885. # 判断是否有广告
  886. if manager.get_pixel_color(index, 700, 1200, log_callback=self.log_message) in ["#E8E3CE"]:
  887. self.log_message(f"模拟器 {index} 点击跳过广告!")
  888. manager.tap(index, 700, 1200, self.log_message)
  889. time.sleep(2)
  890. # 随机翻页间隔
  891. interval_str = self.page_interval_var.get()
  892. if '-' in interval_str:
  893. parts = interval_str.split('-')
  894. if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
  895. intervalNum = random.randint(int(parts[0]), int(parts[1]))
  896. else:
  897. intervalNum = 30
  898. else:
  899. intervalNum = int(interval_str) if interval_str.isdigit() else 30
  900. time.sleep(intervalNum)
  901. manager.swipe(index, 700, 700, 200, 700, 500, self.log_message)
  902. time.sleep(2)
  903. # 加入书签
  904. self.log_message(f"正在加入书架 {index}...")
  905. manager.tap(index, 360, 600, self.log_message)
  906. time.sleep(2)
  907. manager.tap(index, 255, 84, self.log_message)
  908. time.sleep(3)
  909. # 清除应用数据
  910. self.log_message(f"正在清除模拟器 {index} 应用数据...")
  911. manager.clear_app_data(index, self.package_name_var.get(), self.log_message)
  912. time.sleep(2)
  913. # 关闭模拟器
  914. self.log_message(f"正在关闭模拟器 {index}...")
  915. manager.stop_emulator(index)
  916. self.log_message(f"✅ 模拟器 {index} 任务完成")
  917. self.results[index] = True
  918. self.root.after(0, lambda: self.update_emulator_status(index, "任务完成"))
  919. except Exception as e:
  920. self.log_message(f"❌ 模拟器 {index} 执行出错: {e}")
  921. self.results[index] = False
  922. self.root.after(0, lambda: self.update_emulator_status(index, "执行出错"))
  923. finally:
  924. # 减少活跃线程计数
  925. with self.threads_lock:
  926. self.active_threads -= 1
  927. current_active = self.active_threads
  928. self.log_message(f"📊 当前活跃线程数: {current_active}/{max_threads}")
  929. # 释放信号量,让下一个等待的线程开始
  930. self.thread_semaphore.release()
  931. # 启动所有模拟器任务(信号量会自动控制并发数)
  932. for emu in self.selected_emulators:
  933. if self.should_stop:
  934. break
  935. thread = threading.Thread(target=process_emulator, args=(emu,))
  936. thread.start()
  937. threads.append(thread)
  938. # 稍微延迟一下,避免同时启动太多
  939. time.sleep(2)
  940. # 等待所有线程完成
  941. for thread in threads:
  942. thread.join()
  943. success_count = sum(1 for v in self.results.values() if v)
  944. self.log_message(f"\n🎉 任务执行完毕!成功: {success_count}/{len(self.selected_emulators)}")
  945. except Exception as e:
  946. self.log_message(f"❌ 任务执行出错: {e}")
  947. finally:
  948. self.is_running = False
  949. self.is_paused = False
  950. self.pause_btn.config(text="暂停")
  951. # 恢复按钮状态
  952. self.root.after(0, self.reset_buttons)
  953. def run_task2(self):
  954. """执行评价任务(支持并发,出错直接退出不重试)"""
  955. try:
  956. # 获取最大线程数
  957. max_threads = int(self.max_threads_var.get()) if self.max_threads_var.get().isdigit() else 1
  958. self.thread_semaphore = threading.Semaphore(max_threads)
  959. self.active_threads = 0
  960. self.log_message(f"📌 最大并发数: {max_threads}")
  961. threads = []
  962. def process_emulator(emu):
  963. """处理单个模拟器的函数,出错直接退出"""
  964. # 获取信号量,控制并发数
  965. self.thread_semaphore.acquire()
  966. # 增加活跃线程计数
  967. with self.threads_lock:
  968. self.active_threads += 1
  969. current_active = self.active_threads
  970. self.log_message(f"📊 当前活跃线程数: {current_active}/{max_threads}")
  971. index = emu['index']
  972. try:
  973. if self.should_stop:
  974. return
  975. self.log_message(f"\n{'='*50}")
  976. self.log_message(f"开始处理模拟器 {index} ({emu['name']})")
  977. self.log_message(f"{'='*50}")
  978. # 更新状态为运行中
  979. self.root.after(0, lambda: self.update_emulator_status(index, "运行中"))
  980. manager = MuMuEmulatorManager(self.mumu_path_var.get())
  981. # 启动模拟器
  982. self.log_message(f"正在启动模拟器 {index}...")
  983. if not manager.start_emulator(index):
  984. self.log_message(f"❌ 模拟器 {index} 启动失败")
  985. self.results[index] = False
  986. self.root.after(0, lambda: self.update_emulator_status(index, "启动失败"))
  987. return
  988. # 等待就绪
  989. if not manager.wait_for_emulator_ready(index, timeout=180, log_callback=self.log_message):
  990. self.log_message(f"❌ 模拟器 {index} 启动超时")
  991. self.results[index] = False
  992. self.root.after(0, lambda: self.update_emulator_status(index, "启动超时"))
  993. return
  994. time.sleep(5)
  995. if not manager.check_resolution(index, 720, self.log_message):
  996. self.log_message(f"❌ 模拟器 {index} 分辨率不是720,停止任务并关闭模拟器")
  997. manager.stop_emulator(index)
  998. self.results[index] = False
  999. self.root.after(0, lambda: self.update_emulator_status(index, "分辨率错误"))
  1000. return
  1001. # 安装APK
  1002. if not manager.install_apk(index, self.apk_path_var.get(), self.log_message):
  1003. self.log_message(f"⚠️ APK安装失败,但继续执行...")
  1004. # 打开应用
  1005. manager.open_app(index, self.package_name_var.get(), self.log_message)
  1006. # 等待进入主界面
  1007. errNumber = 0
  1008. while True:
  1009. if self.should_stop or self.is_paused:
  1010. while self.is_paused and not self.should_stop:
  1011. time.sleep(1)
  1012. if self.should_stop:
  1013. return
  1014. color560130 = manager.get_pixel_color(index, 560, 130, log_callback=self.log_message)
  1015. if color560130 in ["#EEF8EE", "#F7F7F7"]:
  1016. self.log_message(f"模拟器 {index} 已经进入主界面,继续...")
  1017. break
  1018. elif color560130 in ["#5F635F"]:
  1019. self.log_message(f"模拟器 {index} 需要关闭红包弹窗...")
  1020. manager.tap(index, 640, 260, self.log_message)
  1021. time.sleep(20)
  1022. manager.tap(index, 57, 193, self.log_message)
  1023. elif color560130 in ["#CED0D2"]:
  1024. self.log_message(f"模拟器 {index} 需要关闭广告弹窗...")
  1025. manager.tap(index, 200, 80, self.log_message)
  1026. elif color560130 in ["#F3CEA9"]:
  1027. self.log_message(f"模拟器 {index} 进入错误页面,返回...")
  1028. manager.tap(index, 44, 92, self.log_message)
  1029. time.sleep(20)
  1030. manager.tap(index, 57, 193, self.log_message)
  1031. else:
  1032. errNumber = errNumber + 1
  1033. if errNumber > 30:
  1034. self.log_message(f"模拟器 {index} 连续多次未进入主界面,退出...")
  1035. manager.stop_emulator(index)
  1036. self.results[index] = False
  1037. self.root.after(0, lambda: self.update_emulator_status(index, "进入主界面失败"))
  1038. return
  1039. self.log_message(f"模拟器 {index} 等待进入主界面中...")
  1040. time.sleep(5)
  1041. # 执行打开书籍
  1042. if not self.openBook(manager, index):
  1043. self.results[index] = False
  1044. self.root.after(0, lambda: self.update_emulator_status(index, "打开书籍失败"))
  1045. return
  1046. # 评价
  1047. time.sleep(8)
  1048. manager.tap(index, 680, 95, self.log_message)
  1049. time.sleep(2)
  1050. manager.tap(index, 633, 930, self.log_message)
  1051. # 发表
  1052. time.sleep(5)
  1053. manager.tap(index, 640, 95, self.log_message)
  1054. time.sleep(4)
  1055. # 清除应用数据
  1056. self.log_message(f"正在清除模拟器 {index} 应用数据...")
  1057. manager.clear_app_data(index, self.package_name_var.get(), self.log_message)
  1058. time.sleep(2)
  1059. # 关闭模拟器
  1060. self.log_message(f"正在关闭模拟器 {index}...")
  1061. manager.stop_emulator(index)
  1062. self.log_message(f"✅ 模拟器 {index} 任务完成")
  1063. self.results[index] = True
  1064. self.root.after(0, lambda: self.update_emulator_status(index, "任务完成"))
  1065. except Exception as e:
  1066. self.log_message(f"❌ 模拟器 {index} 执行出错: {e}")
  1067. self.results[index] = False
  1068. self.root.after(0, lambda: self.update_emulator_status(index, "执行出错"))
  1069. finally:
  1070. # 减少活跃线程计数
  1071. with self.threads_lock:
  1072. self.active_threads -= 1
  1073. current_active = self.active_threads
  1074. self.log_message(f"📊 当前活跃线程数: {current_active}/{max_threads}")
  1075. # 释放信号量
  1076. self.thread_semaphore.release()
  1077. # 启动所有模拟器任务
  1078. for emu in self.selected_emulators:
  1079. if self.should_stop:
  1080. break
  1081. thread = threading.Thread(target=process_emulator, args=(emu,))
  1082. thread.start()
  1083. threads.append(thread)
  1084. time.sleep(2)
  1085. # 等待所有线程完成
  1086. for thread in threads:
  1087. thread.join()
  1088. success_count = sum(1 for v in self.results.values() if v)
  1089. self.log_message(f"\n🎉 任务执行完毕!成功: {success_count}/{len(self.selected_emulators)}")
  1090. except Exception as e:
  1091. self.log_message(f"❌ 任务执行出错: {e}")
  1092. finally:
  1093. self.is_running = False
  1094. self.is_paused = False
  1095. self.pause_btn.config(text="暂停")
  1096. # 恢复按钮状态
  1097. self.root.after(0, self.reset_buttons)
  1098. def reset_buttons(self):
  1099. """重置按钮状态"""
  1100. self.load_btn.config(state='normal')
  1101. self.start_read_btn.config(state='normal')
  1102. self.start_comment_btn.config(state='normal')
  1103. self.pause_btn.config(state='disabled', text="暂停")
  1104. self.stop_btn.config(state='disabled')
  1105. def clear_log(self):
  1106. """清空日志"""
  1107. self.log_text.delete(1.0, tk.END)
  1108. def run(self):
  1109. """运行GUI"""
  1110. self.root.mainloop()
  1111. if __name__ == "__main__":
  1112. if datetime.now() < datetime(2026, 5, 25):
  1113. app = MuMuAutoGUI()
  1114. app.run()