Python:看我如何全程自动玩游戏带你飞,直接无敌
生活随笔
收集整理的這篇文章主要介紹了
Python:看我如何全程自动玩游戏带你飞,直接无敌
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
最近我小表妹迷上了玩連連看,玩了一個(gè)星期了還沒通關(guān),真的是菜。
我實(shí)在是看不過去了,直接用python寫了個(gè)腳本代碼,一分鐘一把游戲。
快是快,就是聯(lián)網(wǎng)玩容易被罵,嘿嘿~ 但是,又不是我玩,有什么關(guān)系呢~ 哈哈哈 😎
代碼
導(dǎo)入所需模塊
# -*- coding:utf-8 -*- import cv2 import numpy as np import win32api import win32gui import win32con from PIL import ImageGrab import time import random # 窗體標(biāo)題 用于定位游戲窗體 WINDOW_TITLE = "連連看" # 時(shí)間間隔隨機(jī)生成 [MIN,MAX] TIME_INTERVAL_MAX = 0.06 TIME_INTERVAL_MIN = 0.1 # 游戲區(qū)域距離頂點(diǎn)的x偏移 MARGIN_LEFT = 10 # 游戲區(qū)域距離頂點(diǎn)的y偏移 MARGIN_HEIGHT = 180 # 橫向的方塊數(shù)量 H_NUM = 19 # 縱向的方塊數(shù)量 V_NUM = 11 # 方塊寬度 POINT_WIDTH = 31 # 方塊高度 POINT_HEIGHT = 35 # 空圖像編號 EMPTY_ID = 0 # 切片處理時(shí)候的左上、右下坐標(biāo): SUB_LT_X = 8 SUB_LT_Y = 8 SUB_RB_X = 27 SUB_RB_Y = 27 # 游戲的最多消除次數(shù) MAX_ROUND = 200所需素材在下方或者主頁左側(cè)掃碼獲取
def getGameWindow():# FindWindow(lpClassName=None, lpWindowName=None) 窗口類名 窗口標(biāo)題名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...')# 通過游戲窗體定位# 加上偏移量獲取游戲區(qū)域game_x = game_pos[0] + MARGIN_LEFTgame_y = game_pos[1] + MARGIN_HEIGHT# 從游戲區(qū)域左上開始# 把圖像按照具體大小切割成相同的小塊# 切割標(biāo)準(zhǔn)是按照小塊的橫縱坐標(biāo)all_square = []for x in range(0, H_NUM):for y in range(0, V_NUM):# ndarray的切片方法 : [縱坐標(biāo)起始位置:縱坐標(biāo)結(jié)束為止,橫坐標(biāo)起始位置:橫坐標(biāo)結(jié)束位置]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)# 因?yàn)橛行﹫D片的邊緣會造成干擾,所以統(tǒng)一把圖片往內(nèi)縮小一圈# 對所有的方塊進(jìn)行處理 ,去掉邊緣一圈后返回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# 判斷列表中是否存在相同圖形 # 存在返回進(jìn)行判斷圖片所在的id # 否則返回-1 def isImageExist(img, img_list):i = 0for existed_img in img_list:# 兩個(gè)圖片進(jìn)行比較 返回的是兩個(gè)圖片的標(biāo)準(zhǔn)差b = np.subtract(existed_img, img)# 若標(biāo)準(zhǔn)差全為0 即兩張圖片沒有區(qū)別if not np.any(b):return ii = i + 1return -1def getAllSquareTypes(all_square):print("Init pictures types...")types = []# number列表用來記錄每個(gè)id的出現(xiàn)次數(shù)number = []# 當(dāng)前出現(xiàn)次數(shù)最多的方塊# 這里我們默認(rèn)出現(xiàn)最多的方塊應(yīng)該是空白塊nowid = 0;for square in all_square:nid = isImageExist(square, types)# 如果這個(gè)圖像不存在則插入列表if nid == -1:types.append(square)number.append(1);else:# 若這個(gè)圖像存在則給計(jì)數(shù)器 + 1number[nid] = number[nid] + 1if (number[nid] > number[nowid]):nowid = nid# 更新EMPTY_ID# 即判斷在當(dāng)前這張圖中的空白塊idglobal EMPTY_IDEMPTY_ID = nowidprint('EMPTY_ID = ' + str(EMPTY_ID))return types# 將二維圖片矩陣轉(zhuǎn)換為二維數(shù)字矩陣 # 注意因?yàn)樵谏厦鎸仄燎衅瑫r(shí)是以列為優(yōu)先切片的 # 所以生成的record二維矩陣每行存放的其實(shí)是游戲屏幕中每列的編號 # 換個(gè)說法就是record其實(shí)是游戲屏幕中心對稱后的列表 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# 每列的數(shù)量為V_NUM# 那么當(dāng)當(dāng)前的line列表中存在V_NUM個(gè)方塊時(shí)我們認(rèn)為本列處理完畢if len(line) == V_NUM:print(line);record.append(line)line = []return recorddef canConnect(x1, y1, x2, y2, r):result = r[:]# 如果兩個(gè)圖像中有一個(gè)為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# 判斷一個(gè)拐點(diǎn)可連通if turnOnceCheck(x1, y1, x2, y2, result):return True# 判斷兩個(gè)拐點(diǎn)可連通if turnTwiceCheck(x1, y1, x2, y2, result):return True# 不可聯(lián)通返回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)# 判斷兩個(gè)方塊是否相鄰if (endY - startY) == 1:return True# 判斷兩個(gè)方塊通路上是否都是0,有一個(gè)不是,就說明不能聯(lián)通,返回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)# 判斷兩個(gè)方塊是否相鄰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# 拐點(diǎn)為空,從第一個(gè)點(diǎn)到拐點(diǎn)并且從拐點(diǎn)到第二個(gè)點(diǎn)可通,則整條路可通。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# 遍歷整個(gè)數(shù)組找合適的拐點(diǎn)for i in range(0, len(result)):for j in range(0, len(result[1])):# 不為空不能作為拐點(diǎn)if result[i][j] != EMPTY_ID:continue# 不和被選方塊在同一行列的不能作為拐點(diǎn)if i != x1 and i != x2 and j != y1 and j != y2:continue# 作為交點(diǎn)的方塊不能作為拐點(diǎn)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])):# 當(dāng)前位置非空if result[i][j] != EMPTY_ID:# 再次遍歷地圖 尋找另一個(gè)滿足條件的圖片for m in range(0, len(result)):for n in range(0, len(result[0])):if result[m][n] != EMPTY_ID:# 若可以執(zhí)行消除if canConnect(i, j, m, n, result):# 消除的兩個(gè)位置設(shè)置為空result[i][j] = EMPTY_IDresult[m][n] = EMPTY_IDprint('Remove :' + str(i + 1) + ',' + str(j + 1) + ' and ' + str(m + 1) + ',' + str(n + 1))# 計(jì)算當(dāng)前兩個(gè)位置的圖片在游戲中應(yīng)該存在的位置x1 = game_x + j * POINT_WIDTHy1 = game_y + i * POINT_HEIGHTx2 = game_x + n * POINT_WIDTHy2 = game_y + m * POINT_HEIGHT# 模擬鼠標(biāo)點(diǎn)擊第一個(gè)圖片所在的位置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)# 等待隨機(jī)時(shí)間 ,防止檢測time.sleep(random.uniform(TIME_INTERVAL_MIN, TIME_INTERVAL_MAX))# 模擬鼠標(biāo)點(diǎn)擊第二個(gè)圖片所在的位置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))# 執(zhí)行消除后返回Truereturn Truereturn Falsedef autoRemove(squares, game_pos):game_x = game_pos[0] + MARGIN_LEFTgame_y = game_pos[1] + MARGIN_HEIGHT# 重復(fù)一次消除直到到達(dá)最多消除次數(shù)while True:if not autoRelease(squares, game_x, game_y):# 當(dāng)不再有可消除的方塊時(shí)結(jié)束 , 返回消除數(shù)量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. 講獲取的圖片地圖轉(zhuǎn)換成數(shù)字矩陣result = np.transpose(getAllSquareRecord(all_square_list, types))# vi. 執(zhí)行消除 , 并輸出消除數(shù)量print('The total elimination amount is ' + str(autoRemove(result, game_pos)))尾語
成功沒有快車道,幸福沒有高速路。
所有的成功,都來自不倦地努力和奔跑,所有的幸福都來自平凡的奮斗和堅(jiān)持
——?jiǎng)?lì)志語錄
本文章就寫完啦~感興趣的小伙伴可以復(fù)制代碼去試試
你們的支持是我最大的動(dòng)力!!記得三連哦~ 💕 歡迎大家閱讀往期的文章呀
總結(jié)
以上是生活随笔為你收集整理的Python:看我如何全程自动玩游戏带你飞,直接无敌的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 好用又免费的办公软件
- 下一篇: websocket python爬虫_p