1. 程式人生 > >50行Python程式碼玩轉微信小遊戲"顏色王者"

50行Python程式碼玩轉微信小遊戲"顏色王者"

50行Python程式碼玩轉微信小遊戲”顏色王者”

遊戲模式

在微信小程式裡搜尋“顏色王者”,即可找到該遊戲。
遊戲的目標比拼色彩敏感度。點選圖片中不一樣的色塊即可。

這遊戲前面20多級還是比較簡單的,到後面色塊實在太小,顏色越來越接近以至於到下圖的程度。

工具介紹

  • Python 3.5
  • Android 手機
  • Adb 驅動
  • Python OpenCV庫

原理說明

  1. 首先使用adb截圖,並且推送到電腦
  2. 呼叫OpenCV庫,讀入圖片,把狀態列等區域截掉
  3. findContours函式識別邊框
  4. minEnclosingCircle找出最小外接圓(目的是找出色塊的中心)
  5. 利用畫素值比較出不同的色塊

程式原始碼

import cv2
import os
import time

def compare(rgb1, rgb2):
    if (abs(rgb1[0]-rgb2[0]) < 3 and abs(rgb1[1]-rgb2[1]) < 3 and abs(rgb1[2]-rgb2[2]) < 3):
        return True
    else:
        return False
while True:
    os.system('adb shell screencap -p /sdcard/yanse.png')
    os.system('adb pull /sdcard/yanse.png G:/Python_code/wechat_jump_game-master/yansewangzhe/yanse.png')

    original_image = cv2.imread('G:/Python_code/wechat_jump_game-master/yansewangzhe/yanse.png')
    #選取出圖片中準備識別的部分
    ROIimage = original_image[400:1500, 20:1200]
    res = cv2.resize(ROIimage, (900, 900), interpolation=cv2.INTER_CUBIC)

    gray_img = cv2.cvtColor(res, cv2.COLOR_RGB2GRAY)
    ret, binary_img = cv2.threshold(gray_img, 50, 200, cv2.THRESH_BINARY)
    im, contours, hierarchy = cv2.findContours(binary_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    list1 = []
    list2 = []
    (x0, y0), radius = cv2.minEnclosingCircle(contours[0])
    for c in contours:
        (x, y), radius = cv2.minEnclosingCircle(c)
        if compareColor(res[int(x0), int(y0)], res[int(x), int(y)]):
            list1.append([int(x), int(y)])
        else:
            list2.append([int(x), int(y)])
    print(list1)
    print(list2)
    # 將不同顏色的色塊中心標註黑色圓點
    if len(list1) == 1:
        cv2.circle(res, (list1[0][1], list1[0][0]), 2, (0, 0, 0), 10)
    else:
        cv2.circle(res, (list2[0][1], list2[0][0]), 2, (0, 0, 0), 10)


    cv2.imshow('Window1', res)
    cv2.waitKey()
    cv2.destroyAllWindows()
    time.sleep(1)

實際使用

程式按任意鍵後,會立即再擷取新圖片,執行效果如下。

最終當然是打滿了52級。

Future

後面的小方塊實在太多,對著電腦找點實在麻煩。當然也可以直接讓adb點選,不過懟齊電腦和手機上的畫素點有點麻煩。

PS:最強王者居然有6個人,真是難以想象之前5個人是怎麼識別後面的小方塊的。