comon.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. import threading
  4. import pyautogui
  5. from scriptBase.imgFind import pcacc_img
  6. from scriptBase.mouseClick import pcacc_mouse
  7. import time
  8. import random
  9. import pygetwindow as gw
  10. import re
  11. from PIL import Image
  12. from PIL import ImageFilter
  13. import io
  14. from scriptBase.ocr import *
  15. from scriptBase.record import ScreenRecorder
  16. g_recorder = ScreenRecorder()
  17. def compress_image(image, target_size = 100 * 1024):
  18. # 调整图像尺寸,保持纵横比
  19. image.thumbnail((1024, 1024))
  20. # 尝试不同的压缩质量
  21. quality = 80
  22. compressed_image = io.BytesIO()
  23. while compressed_image.tell() < target_size and quality >= 10:
  24. image.save(compressed_image, format='JPEG', quality=quality)
  25. quality -= 10
  26. compressed_image.seek(0)
  27. compressed_size = len(compressed_image.getvalue())
  28. return compressed_image.getvalue()
  29. '''
  30. def binarize_image(image):
  31. # 将图片转换为黑白格式(二值化)
  32. # 这里使用Pillow库来进行图片二值化
  33. image = image.convert("L") # 将图片转换为灰度图像
  34. threshold = 128 # 设定二值化阈值,0~255之间,通常取128
  35. image = image.point(lambda x: 0 if x < threshold else 255, '1') # 进行二值化处理
  36. return image
  37. '''
  38. def binarize_image(image):
  39. # 将图片转换为灰度图像
  40. image = image.convert("L")
  41. # 降噪处理(中值滤波)
  42. image = image.filter(ImageFilter.MedianFilter(size=3))
  43. # 自适应阈值二值化
  44. threshold = image.point(lambda x: 0 if x < 128 else 255, '1')
  45. return threshold
  46. def waitFindImg(imgPath, waitTime, preWaitTime, isCV=False):
  47. pre = time.time()
  48. if preWaitTime > 0:
  49. myTimeSleep(preWaitTime)
  50. #sleep 0.2s per times
  51. curTime = 0
  52. while waitTime == -1 or curTime < waitTime:
  53. ret, pos_cur = pcacc_img.find_imgs(imgPath, isCV)
  54. if ret:
  55. return ret, pos_cur
  56. else:
  57. myTimeSleep(0.1)
  58. curTime = time.time() - pre
  59. costTime = time.time() - pre
  60. print(f"waitFindImg failed, cost:{costTime}, img:{imgPath}")
  61. return False, None
  62. def waitClickImg_noWait(imgPath, waitTime, preWaitTime, isCV=False):
  63. pre = time.time()
  64. if preWaitTime > 0:
  65. myTimeSleep(preWaitTime)
  66. #sleep 0.2s per times
  67. curTime = 0
  68. while waitTime == -1 or curTime < waitTime:
  69. ret, pos_cur = pcacc_img.find_imgs(imgPath, isCV)
  70. if ret:
  71. pcacc_mouse.click(pos_cur[0], pos_cur[1])
  72. myTimeSleep(0.5)
  73. return True, pos_cur
  74. else:
  75. myTimeSleep(0.1)
  76. curTime = time.time() - pre
  77. costTime = time.time() - pre
  78. print(f"waitClickImg_noWait failed, cost:{costTime}, img:{imgPath}")
  79. return False, (-1, -1)
  80. def waitFindImg_withBool(imgPath, waitTime, preWaitTime, isCV=False):
  81. ret, pos = waitFindImg(imgPath, waitTime, preWaitTime, isCV)
  82. return ret
  83. def waitClickImg_noWait_withBool(imgPath, waitTime, preWaitTime, isCV=False):
  84. ret, pos = waitClickImg_noWait(imgPath, waitTime, preWaitTime, isCV)
  85. return ret
  86. def waitclickMultiImg(imgArr, waitTime, preWaitTime):
  87. if preWaitTime > 0:
  88. myTimeSleep(preWaitTime)
  89. #sleep 0.2s per times
  90. curTime = 0
  91. while waitTime == -1 or curTime < waitTime:
  92. ret, pos_cur = pcacc_img.find_imgArr(imgArr)
  93. if ret:
  94. pcacc_mouse.click(pos_cur[0], pos_cur[1])
  95. myTimeSleep(0.5)
  96. ret, pos_cur = pcacc_img.find_imgArr(imgArr)
  97. if ret == False:
  98. return True, pos_cur
  99. pcacc_mouse.click(pos_cur[0], pos_cur[1])
  100. myTimeSleep(0.5)
  101. ret, pos_cur = pcacc_img.find_imgArr(imgArr)
  102. if ret == False:
  103. return True, pos_cur
  104. else:
  105. return True, pos_cur
  106. else:
  107. myTimeSleep(0.2)
  108. curTime = curTime + 0.2
  109. print("waitclickMultiImg failed", imgArr)
  110. return False, (-1, -1)
  111. def waitClickImg(imgPath, waitTime, preWaitTime, isCV=False):
  112. if preWaitTime > 0:
  113. myTimeSleep(preWaitTime)
  114. #sleep 0.2s per times
  115. curTime = 0
  116. while waitTime == -1 or curTime < waitTime:
  117. ret, pos_cur = pcacc_img.find_imgs(imgPath, isCV)
  118. if ret:
  119. pcacc_mouse.move_mouse(pos_cur[0], pos_cur[1])
  120. ret, pos_cur2 = pcacc_img.find_imgs(imgPath, isCV)
  121. if ret:
  122. pcacc_mouse.click(pos_cur2[0], pos_cur2[1])
  123. else:
  124. pcacc_mouse.click(pos_cur[0], pos_cur[1])
  125. myTimeSleep(0.5)
  126. ret, pos_cur = pcacc_img.find_imgs(imgPath, isCV)
  127. if ret == False:
  128. return True, pos_cur
  129. pcacc_mouse.move_mouse(pos_cur[0], pos_cur[1])
  130. ret, pos_cur2 = pcacc_img.find_imgs(imgPath, isCV)
  131. if ret:
  132. pcacc_mouse.click(pos_cur2[0], pos_cur2[1])
  133. else:
  134. pcacc_mouse.click(pos_cur[0], pos_cur[1])
  135. myTimeSleep(0.5)
  136. ret, pos_cur = pcacc_img.find_imgs(imgPath, isCV)
  137. if ret == False:
  138. return True, pos_cur
  139. else:
  140. return True, pos_cur
  141. else:
  142. myTimeSleep(0.2)
  143. curTime = curTime + 0.2
  144. print("waitClickImg failed", imgPath)
  145. return False, (-1, -1)
  146. def waitClickImg_withBool(imgPath, waitTime, preWaitTime, isCV=False):
  147. ret, pos = waitClickImg(imgPath, waitTime, preWaitTime, isCV)
  148. return ret
  149. def myTimeSleep(curTime , FunStatus=None):
  150. tmpTime = curTime * 1000
  151. randomTime = random.randint(int(tmpTime - tmpTime / 9), int(tmpTime + tmpTime / 9)) / 1000
  152. randomTime = round(randomTime)
  153. while randomTime > 50:
  154. time.sleep(50)
  155. randomTime -= 50
  156. showStr = f'下一轮{randomTime}s'
  157. if FunStatus is not None:
  158. FunStatus(showStr)
  159. print(showStr)
  160. time.sleep(randomTime)
  161. def myTimeSleep_small():
  162. time.sleep(random.randint(200, 1000) / 1000)
  163. def myTimeSleep_big():
  164. time.sleep(random.randint(1200, 2000) / 1000)
  165. def get_random_point(region):
  166. left, top, width, height = region
  167. x = random.randint(left, left + width)
  168. y = random.randint(top, top + height)
  169. return x, y
  170. def get_yys_random_point(region):
  171. dstRegion = yys_getRegion(region, True)
  172. print(dstRegion)
  173. return get_random_point(dstRegion)
  174. def maintain_state(min):
  175. state = True
  176. last_reset_time = time.time()
  177. def inner_func():
  178. nonlocal state, last_reset_time
  179. # 获取当前时间
  180. current_time = time.time()
  181. # 如果距离上次重置的时间大于等于min秒,则将状态重置为True
  182. if current_time - last_reset_time >= min:
  183. state = True
  184. last_reset_time = current_time
  185. # 返回状态值,并将状态置为False
  186. result = state
  187. state = False
  188. return result
  189. return inner_func
  190. def find_window_pos(title):
  191. # 查找窗口
  192. winList = gw.getWindowsWithTitle(title)
  193. if len(winList) == 0:
  194. return False, None
  195. window = gw.getWindowsWithTitle(title)[0] # 替换为你要查找的窗口标题
  196. # 获取位置信息
  197. left = window.left
  198. top = window.top
  199. width = window.width
  200. height = window.height
  201. # 打印位置信息
  202. #print(f'Left: {left}, Top: {top}, Width: {width}, Height: {height}')
  203. if left > 0 and top > 0 and width > 0 and height > 0:
  204. return True, (left, top, width, height)
  205. else:
  206. return False, None
  207. def find_yys_pos():
  208. return find_window_pos('Mumu模拟器12')
  209. def get_first_single_digit(string):
  210. pattern = r'\d' # 匹配一个独立的单个数字
  211. match = re.search(pattern, string)
  212. if match:
  213. return int(match.group()) # 将匹配到的字符串转换为整数
  214. else:
  215. return None
  216. def dragAuto(gamestr, positions):
  217. tmpRet, tmpPos = find_window_pos(gamestr)
  218. if tmpRet == False:
  219. return False
  220. x1 = positions[0] + tmpPos[0] + random.randint(-20, 20)
  221. y1 = positions[1] + tmpPos[1] + random.randint(-20, 20)
  222. x2 = positions[2] + tmpPos[0] + random.randint(-20, 20)
  223. y2 = positions[3] + tmpPos[1] + random.randint(-20, 20)
  224. pcacc_mouse.drag_from(x1, y1, x2, y2)
  225. return True
  226. def ocrAuto(gamestr, positions):
  227. try:
  228. tmpRet, tmpPos = find_window_pos(gamestr)
  229. if tmpRet == False:
  230. return []
  231. x1 = positions[0] + tmpPos[0]
  232. y1 = positions[1] + tmpPos[1]
  233. x2 = positions[2] + tmpPos[0]
  234. y2 = positions[3] + tmpPos[1]
  235. region = (x1, y1, x2, y2)
  236. lineStr = capture_and_ocr(region)
  237. print("识别到:", lineStr)
  238. except:
  239. lineStr = ""
  240. return lineStr
  241. def yys_ocrAuto(positions):
  242. return ocrAuto('Mumu模拟器12', positions)
  243. def yys_dragAuto(positions):
  244. return dragAuto('Mumu模拟器12', positions)
  245. def getRegion(gamestr, region, isWidth):
  246. tmpRet, tmpPos = find_window_pos(gamestr)
  247. if tmpRet == False:
  248. return False
  249. if isWidth:
  250. return (region[0] + tmpPos[0], region[1] + tmpPos[1], region[2] - region[0], region[3] - region[1])
  251. else:
  252. return (region[0] + tmpPos[0], region[1] + tmpPos[1], region[2] + tmpPos[0], region[3] + tmpPos[1])
  253. def game_region():
  254. tmpRet, tmpPos = find_window_pos('Mumu模拟器12',)
  255. return tmpRet, tmpPos
  256. def save_game_screen(fileHeader=""):
  257. try:
  258. regionRet, regionPos = game_region()
  259. screenshot = pyautogui.screenshot(region=regionPos)
  260. curData = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
  261. fileName = "temp_pictures/" + fileHeader + "_" + curData + ".png"
  262. screenshot.save(fileName)
  263. return True
  264. except Exception as e:
  265. print(f"截图保存失败: {e}")
  266. return False
  267. # 创建并启动截图线程
  268. def start_screenshot_thread(fileHeader=""):
  269. screenshot_thread = threading.Thread(
  270. target=save_game_screen,
  271. args=(fileHeader,),
  272. name=f"ScreenshotThread_{fileHeader}"
  273. )
  274. screenshot_thread.start()
  275. return screenshot_thread
  276. def start_recording():
  277. global g_recorder
  278. regionRet, regionPos = game_region()
  279. print("record region,", regionPos)
  280. g_recorder.start_recording(regionPos)
  281. def stop_recording():
  282. global g_recorder
  283. g_recorder.stop_recording()
  284. def yys_getRegion(region, isWidth= False):
  285. return getRegion('Mumu模拟器12', region, isWidth)
  286. def click_waitimg(pos_x,pos_y,img):
  287. retry_times = 3
  288. while retry_times > 0 and waitFindImg_withBool(img,0.4,1) == False:
  289. pcacc_mouse.click(pos_x,pos_y)
  290. retry_times-=1
  291. return retry_times > 0