from PIL import Image import numpy as np import random import time import os def get_screen_shot(): """截取手机屏幕,""" os.system('adb shell screencap -p /sdcard/screen.png') # 获取手机当前截面截图 os.system('adb pull /sdcard/screen.png') # 下载当前截图到当前文件夹 def find_piece_and_board(img_path): """接受一个image,找到棋盘的坐标""" img = Image.open(img_path) # 获取图片尺寸 w,h = img.size # w 1080 h 1920 # 获得图片的像素矩阵 img_pixel = img.load() start_y = None # 以50为步长扫描,提高效率,先确定边界 for i in range(int(h/3),int(h*2/3),50): first_pixel = img_pixel[0,i] # 循环这一行的其他点,如果不是纯色,说明碰到其他棋盘 for j in range(1, w): pixel = img_pixel[j,i] if pixel[0] != first_pixel[0] or pixel[1] !=first_pixel[1] or pixel[2] != first_pixel[2]: start_y = i - 50 if start_y: break left = 0 right = 0 piece_y_max = 0 # 找棋子 for i in range(start_y, int(h*2/3)): flag = True for j in range(int(w/8),int(w*7/8)): # 为了减少开销,左右去掉1/8 pixel = img_pixel[j, i] # 根据棋子最后一行的颜色判断,找到 if (50 < pixel[0] < 60) and (53 < pixel[1] < 63) and (95 <pixel[2] <110): if flag: left = j flag = False right = j piece_y_max = max(i,piece_y_max) piece_x = (left + right) // 2 # y是找到最下面的点 piece_y = piece_y_max - 20 piece = (piece_x, piece_y) # 限制棋盘扫描横坐标 if piece_x < w/2: board_x_start = piece_x + 380 board_x_end = 1000 else: board_x_start = 0 board_x_end = piece_x + 38 # 找棋盘 flag = True for i in range(start_y, int(h * 2 / 3)): first_pixel = img_pixel[0, i] for j in range(board_x_start, board_x_end): pixel = img_pixel[j, i] if abs(pixel[0] - first_pixel[0]) + abs(pixel[1] - first_pixel[1]) + abs(pixel[2] - first_pixel[2]) > 10: if flag: left = j right = j flag = False else: right = j if not flag: break board_x = (left + right) // 2 top_point = img_pixel[board_x, i] board_y = 0 # 往下274个像素的位置开始找位置 # 274 最大的棋盘的高度 for k in range(i+274,i,-1): pixel = img_pixel[board_x, k] if abs(pixel[0] - top_point[0]) + abs(pixel[1] - top_point[1]) + abs(pixel[2] - top_point[2]) < 15: board_y = k break board_y = (board_y + i) // 2 board = (board_x, board_y) return piece, board def get_distance(piece, board): """计算距离""" x1 = piece[0] y1 = piece[1] x2 = board[0] y2 = board[1] distance = ((x1-x2)**2+(y1-y2)**2)**0.5 return distance def jump(distance): press_time = distance * 1.392 point = (random.randint(815, 923),random.randint(1509, 1658)) cmd = 'adb shell input swipe {x1} {y1} {x2} {y2} {time}'.format( x1=point[0], y1=point[1], x2=point[0]+ random.randint(1,3), y2=point[1] + random.randint(1,3), time = int(press_time) ) os.system(cmd) def run(): print("请将手机调整到usb调试并开始游戏") flag = input("请输入y开始游戏:") if flag=='y': while 1 : get_screen_shot() img_path = 'screen.png' piece, board = find_piece_and_board(img_path) print(str(piece) + "--->" + str(board)) distance = get_distance(piece, board) jump(distance) time.sleep(random.randrange(1,3)) else: return if __name__ == '__main__': run()
基于像素分析的找到棋子的中心和下一个格子的中心,然后采用像素数距离跳,并不是特别稳定