1. 程式人生 > 其它 >連連看有點費腦力,於是我直接用Python寫了個自動過關指令碼!太爽了!

連連看有點費腦力,於是我直接用Python寫了個自動過關指令碼!太爽了!

最近女朋友在玩連連看,玩了一個星期了還沒通關,真的是菜。

我實在是看不過去了,直接用python寫了個指令碼程式碼,一分鐘一把遊戲。

快是快,就是聯網玩容易被罵,嘿嘿~

直接上程式碼

模組匯入

import cv2
import numpy as np
import win32api
import win32gui
import win32con
from PIL import ImageGrab
import time
import random

 

窗體標題 用於定位遊戲窗體

WINDOW_TITLE = "連連看"
# Python學習交流群  815624229
# 本專案素材也在群裡可以獲取

 

時間間隔隨機生成 [MIN,MAX]

TIME_INTERVAL_MAX = 0.06
TIME_INTERVAL_MIN = 0.1

 

遊戲區域距離頂點的x偏移

MARGIN_LEFT = 10

 

遊戲區域距離頂點的y偏移

MARGIN_HEIGHT = 180

 

橫向的方塊數量

H_NUM = 19

 

縱向的方塊數量

V_NUM = 11

 

方塊寬度

POINT_WIDTH = 31

 

方塊高度

POINT_HEIGHT = 35

 

空影象編號

EMPTY_ID = 0

 

切片處理時候的左上、右下座標:

SUB_LT_X = 8
SUB_LT_Y = 8
SUB_RB_X = 27
SUB_RB_Y = 27

 

遊戲的最多消除次數

MAX_ROUND = 200

 

獲取窗體座標位置

def getGameWindow():
    # FindWindow(lpClassName=None, lpWindowName=None)  視窗類名 視窗標題名
    window = win32gui.FindWindow(None, WINDOW_TITLE)

    # 沒有定位到遊戲窗體
    while not window:
        
print('Failed to locate the game window , reposition the game window after 10 seconds...') time.sleep(10) window = win32gui.FindWindow(None, WINDOW_TITLE) # 定位到遊戲窗體 # 置頂遊戲視窗 win32gui.SetForegroundWindow(window) pos = win32gui.GetWindowRect(window) print("Game windows at " + str(pos)) return (pos[0], pos[1])

 

獲取螢幕截圖

def getScreenImage():
    print('Shot screen...')
    # 獲取螢幕截圖 Image型別物件
    scim = ImageGrab.grab()
    scim.save('screen.png')
    # 用opencv讀取螢幕截圖
    # 獲取ndarray
    return cv2.imread("screen.png")

 

從截圖中分辨圖片 處理成地圖

def getAllSquare(screen_image, game_pos):
    print('Processing pictures...')
    # 通過遊戲窗體定位
    # 加上偏移量獲取遊戲區域
    game_x = game_pos[0] + MARGIN_LEFT
    game_y = game_pos[1] + MARGIN_HEIGHT

    # 從遊戲區域左上開始
    # 把影象按照具體大小切割成相同的小塊
    # 切割標準是按照小塊的橫縱座標
    all_square = []
    for x in range(0, H_NUM):
        for y in range(0, V_NUM):
            # ndarray的切片方法 : [縱座標起始位置:縱座標結束為止,橫座標起始位置:橫座標結束位置]
            square = screen_image[game_y + y * POINT_HEIGHT:game_y + (y + 1) * POINT_HEIGHT,
                     game_x + x * POINT_WIDTH:game_x + (x + 1) * POINT_WIDTH]
            all_square.append(square)

    # 因為有些圖片的邊緣會造成干擾,所以統一把圖片往內縮小一圈
    # 對所有的方塊進行處理 ,去掉邊緣一圈後返回
    finalresult = []
    for square in all_square:
        s = square[SUB_LT_Y:SUB_RB_Y, SUB_LT_X:SUB_RB_X]
        finalresult.append(s)
    return finalresult

 

判斷列表中是否存在相同圖形
存在返回進行判斷圖片所在的id
否則返回-1

def isImageExist(img, img_list):
    i = 0
    for existed_img in img_list:
        # 兩個圖片進行比較 返回的是兩個圖片的標準差
        b = np.subtract(existed_img, img)
        # 若標準差全為0 即兩張圖片沒有區別
        if not np.any(b):
            return i
        i = i + 1
    return -1

 

獲取所有的方塊型別

def getAllSquareTypes(all_square):
    print("Init pictures types...")
    types = []
    # number列表用來記錄每個id的出現次數
    number = []
    # 當前出現次數最多的方塊
    # 這裡我們默認出現最多的方塊應該是空白塊
    nowid = 0;
    for square in all_square:
        nid = isImageExist(square, types)
        # 如果這個影象不存在則插入列表
        if nid == -1:
            types.append(square)
            number.append(1);
        else:
            # 若這個影象存在則給計數器 + 1
            number[nid] = number[nid] + 1
            if (number[nid] > number[nowid]):
                nowid = nid
    # 更新EMPTY_ID
    # 即判斷在當前這張圖中的空白塊id
    global EMPTY_ID
    EMPTY_ID = nowid
    print('EMPTY_ID = ' + str(EMPTY_ID))
    return types

 

將二維圖片矩陣轉換為二維數字矩陣
注意因為在上面對截圖切片時是以列為優先切片的
所以生成的record二維矩陣每行存放的其實是遊戲螢幕中每列的編號
換個說法就是record其實是遊戲螢幕中心對稱後的列表

def getAllSquareRecord(all_square_list, types):
    print("Change map...")
    record = []
    line = []
    for square in all_square_list:
        num = 0
        for type in types:
            res = cv2.subtract(square, type)
            if not np.any(res):
                line.append(num)
                break
            num += 1
        # 每列的數量為V_NUM
        # 那麼噹噹前的line列表中存在V_NUM個方塊時我們認為本列處理完畢
        if len(line) == V_NUM:
            print(line);
            record.append(line)
            line = []
    return record

 

判斷給出的兩個影象能否消除

def canConnect(x1, y1, x2, y2, r):
    result = r[:]

    # 如果兩個影象中有一個為0 直接返回False
    if result[x1][y1] == EMPTY_ID or result[x2][y2] == EMPTY_ID:
        return False
    if x1 == x2 and y1 == y2:
        return False
    if result[x1][y1] != result[x2][y2]:
        return False
    # 判斷橫向連通
    if horizontalCheck(x1, y1, x2, y2, result):
        return True
    # 判斷縱向連通
    if verticalCheck(x1, y1, x2, y2, result):
        return True
    # 判斷一個拐點可連通
    if turnOnceCheck(x1, y1, x2, y2, result):
        return True
    # 判斷兩個拐點可連通
    if turnTwiceCheck(x1, y1, x2, y2, result):
        return True
    # 不可聯通返回False
    return False

 

判斷橫向聯通

def horizontalCheck(x1, y1, x2, y2, result):
    if x1 == x2 and y1 == y2:
        return False
    if x1 != x2:
        return False
    startY = min(y1, y2)
    endY = max(y1, y2)
    # 判斷兩個方塊是否相鄰
    if (endY - startY) == 1:
        return True
    # 判斷兩個方塊通路上是否都是0,有一個不是,就說明不能聯通,返回false
    for i in range(startY + 1, endY):
        if result[x1][i] != EMPTY_ID:
            return False
    return True

 

判斷縱向聯通

def verticalCheck(x1, y1, x2, y2, result):
    if x1 == x2 and y1 == y2:
        return False

    if y1 != y2:
        return False
    startX = min(x1, x2)
    endX = max(x1, x2)
    # 判斷兩個方塊是否相鄰
    if (endX - startX) == 1:
        return True
    # 判斷兩方塊兒通路上是否可連。
    for i in range(startX + 1, endX):
        if result[i][y1] != EMPTY_ID:
            return False
    return True

 

判斷一個拐點可聯通

def turnOnceCheck(x1, y1, x2, y2, result):
    if x1 == x2 or y1 == y2:
        return False

    cx = x1
    cy = y2
    dx = x2
    dy = y1
    # 拐點為空,從第一個點到拐點並且從拐點到第二個點可通,則整條路可通。
    if result[cx][cy] == EMPTY_ID:
        if horizontalCheck(x1, y1, cx, cy, result) and verticalCheck(cx, cy, x2, y2, result):
            return True
    if result[dx][dy] == EMPTY_ID:
        if verticalCheck(x1, y1, dx, dy, result) and horizontalCheck(dx, dy, x2, y2, result):
            return True
    return False

 

判斷兩個拐點可聯通

def turnTwiceCheck(x1, y1, x2, y2, result):
    if x1 == x2 and y1 == y2:
        return False

    # 遍歷整個陣列找合適的拐點
    for i in range(0, len(result)):
        for j in range(0, len(result[1])):
            # 不為空不能作為拐點
            if result[i][j] != EMPTY_ID:
                continue
            # 不和被選方塊在同一行列的不能作為拐點
            if i != x1 and i != x2 and j != y1 and j != y2:
                continue
            # 作為交點的方塊不能作為拐點
            if (i == x1 and j == y2) or (i == x2 and j == y1):
                continue
            if turnOnceCheck(x1, y1, i, j, result) and (
                    horizontalCheck(i, j, x2, y2, result) or verticalCheck(i, j, x2, y2, result)):
                return True
            if turnOnceCheck(i, j, x2, y2, result) and (
                    horizontalCheck(x1, y1, i, j, result) or verticalCheck(x1, y1, i, j, result)):
                return True
    return False

 

自動消除

def autoRelease(result, game_x, game_y):
    # 遍歷地圖
    for i in range(0, len(result)):
        for j in range(0, len(result[0])):
            # 當前位置非空
            if result[i][j] != EMPTY_ID:
                # 再次遍歷地圖 尋找另一個滿足條件的圖片
                for m in range(0, len(result)):
                    for n in range(0, len(result[0])):
                        if result[m][n] != EMPTY_ID:
                            # 若可以執行消除
                            if canConnect(i, j, m, n, result):
                                # 消除的兩個位置設定為空
                                result[i][j] = EMPTY_ID
                                result[m][n] = EMPTY_ID
                                print('Remove :' + str(i + 1) + ',' + str(j + 1) + ' and ' + str(m + 1) + ',' + str(
                                    n + 1))

                                # 計算當前兩個位置的圖片在遊戲中應該存在的位置
                                x1 = game_x + j * POINT_WIDTH
                                y1 = game_y + i * POINT_HEIGHT
                                x2 = game_x + n * POINT_WIDTH
                                y2 = game_y + m * POINT_HEIGHT

                                # 模擬滑鼠點選第一個圖片所在的位置
                                win32api.SetCursorPos((x1 + 15, y1 + 18))
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x1 + 15, y1 + 18, 0, 0)
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x1 + 15, y1 + 18, 0, 0)

                                # 等待隨機時間 ,防止檢測
                                time.sleep(random.uniform(TIME_INTERVAL_MIN, TIME_INTERVAL_MAX))

                                # 模擬滑鼠點選第二個圖片所在的位置
                                win32api.SetCursorPos((x2 + 15, y2 + 18))
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x2 + 15, y2 + 18, 0, 0)
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x2 + 15, y2 + 18, 0, 0)
                                time.sleep(random.uniform(TIME_INTERVAL_MIN, TIME_INTERVAL_MAX))
                                # 執行消除後返回True
                                return True
    return False

 

效果的話得上傳視訊,截圖展現不出來效果,大家可以自行試試。

 

全部程式碼

# -*- coding:utf-8 -*-
import cv2
import numpy as np
import win32api
import win32gui
import win32con
from PIL import ImageGrab
import time
import random

# 窗體標題  用於定位遊戲窗體
WINDOW_TITLE = "連連看"
# 時間間隔隨機生成 [MIN,MAX]
TIME_INTERVAL_MAX = 0.06
TIME_INTERVAL_MIN = 0.1
# 遊戲區域距離頂點的x偏移
MARGIN_LEFT = 10
# 遊戲區域距離頂點的y偏移
MARGIN_HEIGHT = 180
# 橫向的方塊數量
H_NUM = 19
# 縱向的方塊數量
V_NUM = 11
# 方塊寬度
POINT_WIDTH = 31
# 方塊高度
POINT_HEIGHT = 35
# 空影象編號
EMPTY_ID = 0
# 切片處理時候的左上、右下座標:
SUB_LT_X = 8
SUB_LT_Y = 8
SUB_RB_X = 27
SUB_RB_Y = 27
# 遊戲的最多消除次數
MAX_ROUND = 200


def getGameWindow():
    # FindWindow(lpClassName=None, lpWindowName=None)  視窗類名 視窗標題名
    window = win32gui.FindWindow(None, WINDOW_TITLE)

    # 沒有定位到遊戲窗體
    while not window:
        print('Failed to locate the game window , reposition the game window after 10 seconds...')
        time.sleep(10)
        window = win32gui.FindWindow(None, WINDOW_TITLE)

    # 定位到遊戲窗體
    # 置頂遊戲視窗
    win32gui.SetForegroundWindow(window)
    pos = win32gui.GetWindowRect(window)
    print("Game windows at " + str(pos))
    return (pos[0], pos[1])

def getScreenImage():
    print('Shot screen...')
    # 獲取螢幕截圖 Image型別物件
    scim = ImageGrab.grab()
    scim.save('screen.png')
    # 用opencv讀取螢幕截圖
    # 獲取ndarray
    return cv2.imread("screen.png")

def getAllSquare(screen_image, game_pos):
    print('Processing pictures...')
    # 通過遊戲窗體定位
    # 加上偏移量獲取遊戲區域
    game_x = game_pos[0] + MARGIN_LEFT
    game_y = game_pos[1] + MARGIN_HEIGHT

    # 從遊戲區域左上開始
    # 把影象按照具體大小切割成相同的小塊
    # 切割標準是按照小塊的橫縱座標
    all_square = []
    for x in range(0, H_NUM):
        for y in range(0, V_NUM):
            # ndarray的切片方法 : [縱座標起始位置:縱座標結束為止,橫座標起始位置:橫座標結束位置]
            square = screen_image[game_y + y * POINT_HEIGHT:game_y + (y + 1) * POINT_HEIGHT,
                     game_x + x * POINT_WIDTH:game_x + (x + 1) * POINT_WIDTH]
            all_square.append(square)

    # 因為有些圖片的邊緣會造成干擾,所以統一把圖片往內縮小一圈
    # 對所有的方塊進行處理 ,去掉邊緣一圈後返回
    finalresult = []
    for square in all_square:
        s = square[SUB_LT_Y:SUB_RB_Y, SUB_LT_X:SUB_RB_X]
        finalresult.append(s)
    return finalresult


# 判斷列表中是否存在相同圖形
# 存在返回進行判斷圖片所在的id
# 否則返回-1
def isImageExist(img, img_list):
    i = 0
    for existed_img in img_list:
        # 兩個圖片進行比較 返回的是兩個圖片的標準差
        b = np.subtract(existed_img, img)
        # 若標準差全為0 即兩張圖片沒有區別
        if not np.any(b):
            return i
        i = i + 1
    return -1

def getAllSquareTypes(all_square):
    print("Init pictures types...")
    types = []
    # number列表用來記錄每個id的出現次數
    number = []
    # 當前出現次數最多的方塊
    # 這裡我們默認出現最多的方塊應該是空白塊
    nowid = 0;
    for square in all_square:
        nid = isImageExist(square, types)
        # 如果這個影象不存在則插入列表
        if nid == -1:
            types.append(square)
            number.append(1);
        else:
            # 若這個影象存在則給計數器 + 1
            number[nid] = number[nid] + 1
            if (number[nid] > number[nowid]):
                nowid = nid
    # 更新EMPTY_ID
    # 即判斷在當前這張圖中的空白塊id
    global EMPTY_ID
    EMPTY_ID = nowid
    print('EMPTY_ID = ' + str(EMPTY_ID))
    return types


# 將二維圖片矩陣轉換為二維數字矩陣
# 注意因為在上面對截圖切片時是以列為優先切片的
# 所以生成的record二維矩陣每行存放的其實是遊戲螢幕中每列的編號
# 換個說法就是record其實是遊戲螢幕中心對稱後的列表
def getAllSquareRecord(all_square_list, types):
    print("Change map...")
    record = []
    line = []
    for square in all_square_list:
        num = 0
        for type in types:
            res = cv2.subtract(square, type)
            if not np.any(res):
                line.append(num)
                break
            num += 1
        # 每列的數量為V_NUM
        # 那麼噹噹前的line列表中存在V_NUM個方塊時我們認為本列處理完畢
        if len(line) == V_NUM:
            print(line);
            record.append(line)
            line = []
    return record

def canConnect(x1, y1, x2, y2, r):
    result = r[:]

    # 如果兩個影象中有一個為0 直接返回False
    if result[x1][y1] == EMPTY_ID or result[x2][y2] == EMPTY_ID:
        return False
    if x1 == x2 and y1 == y2:
        return False
    if result[x1][y1] != result[x2][y2]:
        return False
    # 判斷橫向連通
    if horizontalCheck(x1, y1, x2, y2, result):
        return True
    # 判斷縱向連通
    if verticalCheck(x1, y1, x2, y2, result):
        return True
    # 判斷一個拐點可連通
    if turnOnceCheck(x1, y1, x2, y2, result):
        return True
    # 判斷兩個拐點可連通
    if turnTwiceCheck(x1, y1, x2, y2, result):
        return True
    # 不可聯通返回False
    return False

def horizontalCheck(x1, y1, x2, y2, result):
    if x1 == x2 and y1 == y2:
        return False
    if x1 != x2:
        return False
    startY = min(y1, y2)
    endY = max(y1, y2)
    # 判斷兩個方塊是否相鄰
    if (endY - startY) == 1:
        return True
    # 判斷兩個方塊通路上是否都是0,有一個不是,就說明不能聯通,返回false
    for i in range(startY + 1, endY):
        if result[x1][i] != EMPTY_ID:
            return False
    return True

def verticalCheck(x1, y1, x2, y2, result):
    if x1 == x2 and y1 == y2:
        return False

    if y1 != y2:
        return False
    startX = min(x1, x2)
    endX = max(x1, x2)
    # 判斷兩個方塊是否相鄰
    if (endX - startX) == 1:
        return True
    # 判斷兩方塊兒通路上是否可連。
    for i in range(startX + 1, endX):
        if result[i][y1] != EMPTY_ID:
            return False
    return True


def turnOnceCheck(x1, y1, x2, y2, result):
    if x1 == x2 or y1 == y2:
        return False

    cx = x1
    cy = y2
    dx = x2
    dy = y1
    # 拐點為空,從第一個點到拐點並且從拐點到第二個點可通,則整條路可通。
    if result[cx][cy] == EMPTY_ID:
        if horizontalCheck(x1, y1, cx, cy, result) and verticalCheck(cx, cy, x2, y2, result):
            return True
    if result[dx][dy] == EMPTY_ID:
        if verticalCheck(x1, y1, dx, dy, result) and horizontalCheck(dx, dy, x2, y2, result):
            return True
    return False


def turnTwiceCheck(x1, y1, x2, y2, result):
    if x1 == x2 and y1 == y2:
        return False

    # 遍歷整個陣列找合適的拐點
    for i in range(0, len(result)):
        for j in range(0, len(result[1])):
            # 不為空不能作為拐點
            if result[i][j] != EMPTY_ID:
                continue
            # 不和被選方塊在同一行列的不能作為拐點
            if i != x1 and i != x2 and j != y1 and j != y2:
                continue
            # 作為交點的方塊不能作為拐點
            if (i == x1 and j == y2) or (i == x2 and j == y1):
                continue
            if turnOnceCheck(x1, y1, i, j, result) and (
                    horizontalCheck(i, j, x2, y2, result) or verticalCheck(i, j, x2, y2, result)):
                return True
            if turnOnceCheck(i, j, x2, y2, result) and (
                    horizontalCheck(x1, y1, i, j, result) or verticalCheck(x1, y1, i, j, result)):
                return True
    return False


def autoRelease(result, game_x, game_y):
    # 遍歷地圖
    for i in range(0, len(result)):
        for j in range(0, len(result[0])):
            # 當前位置非空
            if result[i][j] != EMPTY_ID:
                # 再次遍歷地圖 尋找另一個滿足條件的圖片
                for m in range(0, len(result)):
                    for n in range(0, len(result[0])):
                        if result[m][n] != EMPTY_ID:
                            # 若可以執行消除
                            if canConnect(i, j, m, n, result):
                                # 消除的兩個位置設定為空
                                result[i][j] = EMPTY_ID
                                result[m][n] = EMPTY_ID
                                print('Remove :' + str(i + 1) + ',' + str(j + 1) + ' and ' + str(m + 1) + ',' + str(
                                    n + 1))

                                # 計算當前兩個位置的圖片在遊戲中應該存在的位置
                                x1 = game_x + j * POINT_WIDTH
                                y1 = game_y + i * POINT_HEIGHT
                                x2 = game_x + n * POINT_WIDTH
                                y2 = game_y + m * POINT_HEIGHT

                                # 模擬滑鼠點選第一個圖片所在的位置
                                win32api.SetCursorPos((x1 + 15, y1 + 18))
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x1 + 15, y1 + 18, 0, 0)
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x1 + 15, y1 + 18, 0, 0)

                                # 等待隨機時間 ,防止檢測
                                time.sleep(random.uniform(TIME_INTERVAL_MIN, TIME_INTERVAL_MAX))

                                # 模擬滑鼠點選第二個圖片所在的位置
                                win32api.SetCursorPos((x2 + 15, y2 + 18))
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x2 + 15, y2 + 18, 0, 0)
                                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x2 + 15, y2 + 18, 0, 0)
                                time.sleep(random.uniform(TIME_INTERVAL_MIN, TIME_INTERVAL_MAX))
                                # 執行消除後返回True
                                return True
    return False


def autoRemove(squares, game_pos):
    game_x = game_pos[0] + MARGIN_LEFT
    game_y = game_pos[1] + MARGIN_HEIGHT
    # 重複一次消除直到到達最多消除次數
    while True:
        if not autoRelease(squares, game_x, game_y):
            # 當不再有可消除的方塊時結束 , 返回消除數量
            return


if __name__ == '__main__':
    random.seed()
    # i. 定位遊戲窗體
    game_pos = getGameWindow()
    time.sleep(1)
    # ii. 獲取螢幕截圖
    screen_image = getScreenImage()
    # iii. 對截圖切片,形成一張二維地圖
    all_square_list = getAllSquare(screen_image, game_pos)
    # iv. 獲取所有型別的圖形,並編號
    types = getAllSquareTypes(all_square_list)
    # v. 講獲取的圖片地圖轉換成數字矩陣
    result = np.transpose(getAllSquareRecord(all_square_list, types))
    # vi. 執行消除 , 並輸出消除數量
    print('The total elimination amount is ' + str(autoRemove(result, game_pos)))

 

兄弟們快去試試吧