要实现一个金铲铲之战的自动拿牌工具,需要结合图像识别和自动化操作技术。以下是分步实现的思路和代码:
import cv2
import numpy as np
import pyautogui
import time
from PIL import ImageGrab
# 配置参数
REFRESH_POS = (1600, 900) # 刷新商店按钮位置
BUY_POSITIONS = [ # 商店卡牌购买位置
(1100, 900),
(1220, 900),
(1340, 900),
(1460, 900),
(1580, 900)
]
# 加载棋子模板(需要提前截取)
champion_templates = {
"zed": cv2.imread('templates/zed.png', 0),
"yasuo": cv2.imread('templates/yasuo.png', 0),
# 添加更多棋子模板...
}
def capture_screen():
"""捕获游戏区域截图"""
return np.array(ImageGrab.grab(bbox=(0,0,1920,1080)))
def find_champions(screen):
"""使用模板匹配识别棋子"""
gray = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
matches = []
for name, template in champion_templates.items():
res = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
matches.append({
"name": name,
"position": (pt[0], pt[1])
})
return matches
def auto_buy():
"""执行购买操作"""
# 刷新商店
pyautogui.click(REFRESH_POS)
time.sleep(0.5)
# 购买所有匹配的棋子
screen = capture_screen()
matches = find_champions(screen)
for match in matches:
x, y = match['position']
# 检查是否在商店区域
if y > 800 and 1000 < x < 1700:
pyautogui.click(x+50, y+50) # 点击购买按钮
time.sleep(0.2)
def main_loop():
"""主循环"""
while True:
auto_buy()
time.sleep(1) # 每次操作间隔
if __name__ == "__main__":
main_loop()
关键实现步骤:
1.屏幕捕获:
使用PIL的ImageGrab捕获屏幕
可以根据游戏窗口位置调整截图区域
2.图像识别:
使用OpenCV进行模板匹配
需要预先准备棋子模板图片
调整阈值(threshold)平衡识别精度和召回率
3.自动化操作:
使用pyautogui模拟鼠标点击
需要根据实际屏幕分辨率校准坐标
添加操作间隔防止检测
4.策略逻辑:
需要扩展阵容判断逻辑
添加经济管理模块(识别金币数量)
实现升级决策逻辑
改进方向:
使用更先进的识别方案:
# 使用YOLO进行目标检测(需要训练自定义模型)
model = YOLO('best.pt')
results = model(screen)
添加状态检测:
def get_game_state():
# OCR识别金币、等级等信息
gold_region = (1800, 50, 1900, 80)
gold_img = ImageGrab.grab(gold_region)
gold = pytesseract.image_to_string(gold_img)
return {"gold": int(gold)}
决策逻辑:
def should_refresh(gold):
return gold > 50
def buy_strategy(matches):
# 优先购买目标棋子
priority_list = ["zed", "yasuo"]
for target in priority_list:
if any(m['name'] == target for m in matches):
return target
注意事项:
需要手动准备棋子模板图片(保存在templates目录)
坐标需要根据实际分辨率调整
需要管理员权限运行
建议在实际使用前先测试各个模块功能,可以通过显示识别结果可视化来调试:
def debug_show(matches):
screen = capture_screen()
for m in matches:
cv2.rectangle(screen, m['position'],
(m['position'][0]+50, m['position'][1]+50),
(0,255,0), 2)
cv2.imshow('Debug', screen)
cv2.waitKey(1)