MuMu.py 57 KB

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