1. 程式人生 > >用python玩跳一跳

用python玩跳一跳

微信跳一跳被同學說是淘寶買的,委屈巴巴,jpg。為了證明清白,把實現過程寫下來。

遊戲人物跳躍的距離是由按壓時間決定的,所以基本原理是

1.利用adb的adb shell screencap -p/**/**/的命令進行截圖

2.將截下來的圖pull到電腦上

3.點選當前位置和要跳位置,計算距離

4.計算按壓時間

5.模擬按壓

由於我沒有mac,沒辦法對蘋果進行模擬控制,只能用adb實現對安卓手機的控制。

直接貼程式碼

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from PIL import Image
import math
import time
import os

os.chdir(r'C:\Users\zhu\platform-tools')    #改變當前工作路徑
fig = plt.figure()
index = 0
cor = [0, 0]
pull_screenshot()
img = np.array(Image.open('1.png'))    #將圖片轉化為numpy的array陣列
update = True
click_count = 0 #計算點選次數,需要兩次
distancesave = []
def pull_screenshot():
    os.system('adb shell screencap -p /sdcard/1.png')
    os.system('adb pull /sdcard/1.png .')


def jump(distance):
    press_time = distance * 1.3    #計算按壓時間,機型不同,係數不同。
    press_time = int(press_time)   #強制轉化
    cmd = 'adb shell input swipe 320 410 320 410 ' + str(press_time)  # 控制按壓時間。這個為滑動命令,由於滑動前後的點都為320,410.所以相當於長按一點
    print(cmd)
    os.system(cmd)   #利用adb控制手機按壓
def update_data():
    return np.array(Image.open('1.png'))


im = plt.imshow(img, animated=True)


def updatefig(*args):     #更新函式
    global update
    if update:
        time.sleep(1)     #停一秒
        pull_screenshot()
        im.set_array(update_data())
        update = False
    return im,


def onClick(event):
    global update
    global ix, iy
    global click_count
    global distancesave

    # next screenshot

    ix, iy = event.xdata, event.ydata  #記錄點選的座標
    coords = []
    coords.append((ix, iy)) 
    cor.append(coords)  #新增座標到列表中

    click_count += 1 
    if click_count > 1:  #點選兩下才開始工作
        click_count = 0  #清零

        cor1 = distancesave.pop() #取出座標
        cor2 = distancesave.pop()

        distance = (cor1[0][0] - cor2[0][0]) ** 2 + (cor1[0][1] - cor2[0][1]) ** 2  
        distance = distance ** 0.5  #計算座標距離

        #print
        #'distance = ', distance
        jump(distance)
        update = True


fig.canvas.mpl_connect('button_press_event', onClick)
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True) 
plt.show()
有大佬已寫出自動執行程式,可以在github查詢。