Python跳一跳腳本用法介紹

YAE7W 數碼 2

本文將詳細解釋如何使用Python編寫跳一跳遊戲腳本。

在編寫跳一跳腳本之前,需要先安裝adb和Python。

adb可以通過Android SDK平台工具包獲取。

Python可以通過官方網站下載安裝。

# 安裝adb
sudo apt-get install android-tools-adb

# 安裝Python
sudo apt-get install python

可以通過adb命令獲取手機屏幕截圖,並使用Pillow庫解析截圖獲取遊戲中小人和目標方塊之間的距離。同時,還需要獲取遊戲中方塊的坐標信息來進行跳躍操作。

import os
import time
import subprocess
from PIL import Image, ImageFilter

# 獲取坐標信息
def get_board():
    cmd = 'adb shell wm size'
    output = subprocess.check_output(cmd.split())
    display = str(output).split()[2].split('x')
    return {'x': int(display[0]), 'y': int(display[1])}

# 獲取遊戲截圖
def get_screenshot():
    cmd = 'adb shell screencap -p /sdcard/%s.png'
    filename = str(int(time.time()))
    os.system(cmd % filename)
    os.system('adb pull /sdcard/%s.png .' % filename)

    # 解析截圖
    screenshot = Image.open('%s.png' % filename)
    screenshot = screenshot.filter(ImageFilter.FIND_EDGES)
    screenshot.save('%s_filter.png' % filename)

    return screenshot

使用adb命令實現跳躍操作。

# 模擬跳躍
def jump(distance):
    press_time = distance * 3 / 1000
    cmd = 'adb shell input swipe %s %s %s %s %s' % (int(board['x']/2), int(board['y']*4/5), int(board['x']/2), int(board['y']*4/5), int(press_time))
    os.system(cmd)
import os
import time
import subprocess
from PIL import Image, ImageFilter

# 獲取坐標信息
def get_board():
    cmd = 'adb shell wm size'
    output = subprocess.check_output(cmd.split())
    display = str(output).split()[2].split('x')
    return {'x': int(display[0]), 'y': int(display[1])}

# 獲取遊戲截圖
def get_screenshot():
    cmd = 'adb shell screencap -p /sdcard/%s.png'
    filename = str(int(time.time()))
    os.system(cmd % filename)
    os.system('adb pull /sdcard/%s.png .' % filename)

    # 解析截圖
    screenshot = Image.open('%s.png' % filename)
    screenshot = screenshot.filter(ImageFilter.FIND_EDGES)
    screenshot.save('%s_filter.png' % filename)

    return screenshot

# 模擬跳躍
def jump(distance):
    press_time = distance * 3 / 1000
    cmd = 'adb shell input swipe %s %s %s %s %s' % (int(board['x']/2), int(board['y']*4/5), int(board['x']/2), int(board['y']*4/5), int(press_time))
    os.system(cmd)

if __name__ == '__main__':
    board = get_board()
    while True:
        screenshot = get_screenshot()
        distance = 100 # 根據實際情況計算跳躍距離
        jump(distance)

通過此腳本可以方便地模擬跳一跳遊戲,並在實際應用中做出相應的優化和修改。

回復

共1條回復 我來回復
  • 暫無回復內容