借鉴: 一百行代码实现微信跳一跳
之前需要安装adb
开启服务:
adb nodaemon server
显示设备:
adb devices
代码:
import math import os import tempfile import time from functools import reduce from PIL import Image BACKGROUND_POS = (, ) DISTANCE_TO_TIME_RATIO = 1.35 SCREENSHOT_PATH = tempfile.gettempdir() + "/screenshot.png" def calculate_jump_distance(): im = Image.open(SCREENSHOT_PATH) background_rgb = im.getpixel(BACKGROUND_POS) role_pos_list = None vertex1_pos = None block_background_rgb = None vertex2_pos = None role_line_flag = True for y in range(BACKGROUND_POS[], im.height): if role_pos_list and role_line_flag: break role_line_flag = True vertex2_line_flag = True for x in range(BACKGROUND_POS[], im.width): current_rgb = im.getpixel((x, y)) next_rgb = im.getpixel((x + , y)) if x + < im.width else (, , ) # 识别顶点1 if x > BACKGROUND_POS[] and y > BACKGROUND_POS[] and not vertex1_pos and not is_similar(background_rgb, current_rgb) and is_similar(current_rgb, next_rgb): vertex1_pos = (x, y) block_background_rgb = current_rgb # 识别顶点2 if block_background_rgb and vertex2_line_flag and is_similar(current_rgb, block_background_rgb, ): vertex2_line_flag = False if vertex2_pos: if x < vertex2_pos[] and vertex2_pos[] - x < and y - vertex2_pos[] < : vertex2_pos = (x, y) else: vertex2_pos = (x, y) # 识别小人 if is_part_of_role(current_rgb): if role_line_flag: role_pos_list = [] role_line_flag = False role_pos_list.append((x, y)) if len(role_pos_list) == : raise Exception('无法识别小人位置!!!') pos_sum = reduce((lambda o1, o2: (o1[] + o2[], o1[] + o2[])), role_pos_list) role_pos = (int(pos_sum[] / len(role_pos_list)), int(pos_sum[] / len(role_pos_list))) destination_pos = (vertex1_pos[], vertex2_pos[]) return int(linear_distance(role_pos, destination_pos)) def is_part_of_role(rgb): return < rgb[] < and < rgb[] < and < rgb[] < def linear_distance(xy1, xy2): return math.sqrt(pow(xy1[] - xy2[], ) + pow(xy1[] - xy2[], )) def is_similar(rgb1, rgb2, degree=): return abs(rgb1[] - rgb2[]) <= degree and abs(rgb1[] - rgb2[]) <= degree and abs(rgb1[] - rgb2[]) <= degree def screenshot(): os.system("adb shell screencap -p /mnt/sdcard/screencap.png") os.system("adb pull /mnt/sdcard/screencap.png {} >> {}/jump.out".format(SCREENSHOT_PATH, tempfile.gettempdir())) def jump(touch_time): os.system("adb shell input swipe 0 0 0 0 {}".format(touch_time)) def distance2time(distance): return int(distance * DISTANCE_TO_TIME_RATIO) if __name__ == '__main__': count = while True: screenshot() distance = calculate_jump_distance() touch_time = distance2time(distance) jump(touch_time) print("#{}: distance={}, time={}".format(count, distance, touch_time)) count += time.sleep()