Python:看我如何全程自动玩游戏带你飞,直接无敌
生活随笔
收集整理的這篇文章主要介紹了
Python:看我如何全程自动玩游戏带你飞,直接无敌
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
最近我小表妹迷上了玩連連看,玩了一個星期了還沒通關,真的是菜。
我實在是看不過去了,直接用python寫了個腳本代碼,一分鐘一把游戲。
快是快,就是聯網玩容易被罵,嘿嘿~ 但是,又不是我玩,有什么關系呢~ 哈哈哈 😎
代碼
導入所需模塊
# -*- 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讀取屏幕截圖# 獲取ndarrayreturn cv2.imread("screen.png")def getAllSquare(screen_image, game_pos):print('Processing pictures...')# 通過游戲窗體定位# 加上偏移量獲取游戲區域game_x = game_pos[0] + MARGIN_LEFTgame_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 = 0for existed_img in img_list:# 兩個圖片進行比較 返回的是兩個圖片的標準差b = np.subtract(existed_img, img)# 若標準差全為0 即兩張圖片沒有區別if not np.any(b):return ii = i + 1return -1def 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:# 若這個圖像存在則給計數器 + 1number[nid] = number[nid] + 1if (number[nid] > number[nowid]):nowid = nid# 更新EMPTY_ID# 即判斷在當前這張圖中的空白塊idglobal EMPTY_IDEMPTY_ID = nowidprint('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 = 0for type in types:res = cv2.subtract(square, type)if not np.any(res):line.append(num)breaknum += 1# 每列的數量為V_NUM# 那么當當前的line列表中存在V_NUM個方塊時我們認為本列處理完畢if len(line) == V_NUM:print(line);record.append(line)line = []return recorddef canConnect(x1, y1, x2, y2, r):result = r[:]# 如果兩個圖像中有一個為0 直接返回Falseif result[x1][y1] == EMPTY_ID or result[x2][y2] == EMPTY_ID:return Falseif x1 == x2 and y1 == y2:return Falseif 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# 不可聯通返回Falsereturn Falsedef horizontalCheck(x1, y1, x2, y2, result):if x1 == x2 and y1 == y2:return Falseif x1 != x2:return FalsestartY = min(y1, y2)endY = max(y1, y2)# 判斷兩個方塊是否相鄰if (endY - startY) == 1:return True# 判斷兩個方塊通路上是否都是0,有一個不是,就說明不能聯通,返回falsefor i in range(startY + 1, endY):if result[x1][i] != EMPTY_ID:return Falsereturn Truedef verticalCheck(x1, y1, x2, y2, result):if x1 == x2 and y1 == y2:return Falseif y1 != y2:return FalsestartX = 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 Falsereturn Truedef turnOnceCheck(x1, y1, x2, y2, result):if x1 == x2 or y1 == y2:return Falsecx = x1cy = y2dx = x2dy = y1# 拐點為空,從第一個點到拐點并且從拐點到第二個點可通,則整條路可通。if result[cx][cy] == EMPTY_ID:if horizontalCheck(x1, y1, cx, cy, result) and verticalCheck(cx, cy, x2, y2, result):return Trueif result[dx][dy] == EMPTY_ID:if verticalCheck(x1, y1, dx, dy, result) and horizontalCheck(dx, dy, x2, y2, result):return Truereturn Falsedef 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):continueif turnOnceCheck(x1, y1, i, j, result) and (horizontalCheck(i, j, x2, y2, result) or verticalCheck(i, j, x2, y2, result)):return Trueif turnOnceCheck(i, j, x2, y2, result) and (horizontalCheck(x1, y1, i, j, result) or verticalCheck(x1, y1, i, j, result)):return Truereturn Falsedef 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_IDresult[m][n] = EMPTY_IDprint('Remove :' + str(i + 1) + ',' + str(j + 1) + ' and ' + str(m + 1) + ',' + str(n + 1))# 計算當前兩個位置的圖片在游戲中應該存在的位置x1 = game_x + j * POINT_WIDTHy1 = game_y + i * POINT_HEIGHTx2 = game_x + n * POINT_WIDTHy2 = 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))# 執行消除后返回Truereturn Truereturn Falsedef autoRemove(squares, game_pos):game_x = game_pos[0] + MARGIN_LEFTgame_y = game_pos[1] + MARGIN_HEIGHT# 重復一次消除直到到達最多消除次數while True:if not autoRelease(squares, game_x, game_y):# 當不再有可消除的方塊時結束 , 返回消除數量returnif __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)))尾語
成功沒有快車道,幸福沒有高速路。
所有的成功,都來自不倦地努力和奔跑,所有的幸福都來自平凡的奮斗和堅持
——勵志語錄
本文章就寫完啦~感興趣的小伙伴可以復制代碼去試試
你們的支持是我最大的動力!!記得三連哦~ 💕 歡迎大家閱讀往期的文章呀
總結
以上是生活随笔為你收集整理的Python:看我如何全程自动玩游戏带你飞,直接无敌的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 好用又免费的办公软件
- 下一篇: Springcloud服务调用Feign