Computer vision玩转游戏--kick-ya-chop
作者:互联网
Computer vision玩转游戏--kick-ya-chop
运行环境
surface电脑
kick-ya-chop是一个网页端的flash游戏
项目来源
https://github.com/ClarityCoders/ComputerVision-OpenCV/tree/master/Lesson3-TemplateMatching
虽然作者在油管上讲的是cv自动采摘农场的作物, 但实际给出的代码只有这个空手道的小游戏(https://www.addictinggames.com/clicker/kick-ya-chop)
运行方式以及效果图
直接分屏, 左边运行网页端的flash游戏, 右边跑python脚本。
代码
import keyboard
import mss
import cv2
import numpy
from time import time, sleep
import pyautogui
# 一些宏变量的定义
pyautogui.PAUSE = 0
left = True
# 动画中的人物可以通过点击鼠标向左, 向右. 这里需要根据自己的电脑屏幕设定鼠标的落点坐标
JUMP_LEFT=(250, 600)
JUMP_RIGHT=(900, 600)
x = JUMP_LEFT[0]
y = JUMP_LEFT[1]
sct = mss.mss()
# 完整画幅
# 'width': 2600,
# 'height': 1800
dimensions = {
'left': 0,
'top': 0,
'width': 1368,
'height': 1800
# 'height': 912
}
# scr = numpy.array(sct.grab(dimensions))
# cv2.imshow('Screen sct', scr)
# cv2.waitKey(-1)
# width=100, h=30
dimensions_left = {
'left': 320,
'top': 1100,
'width': 290,
'height': 60
}
dimensions_right = {
'left': 780,
'top': 1100,
'width': 290,
'height': 60
}
# 模板匹配的阈值, 可以自己设置
MATCHING_TH=0.5
# 动画中人物打击的时间间隔, 这值越小,打击速度越快
KICKING_TIME=0.2
#Tag: 程序开始
print("Press 's' to start playing.")
print("Once started press 'q' to quit.")
keyboard.wait('s')
wood_left = cv2.imread('woodleft.jpg')
wood_right = cv2.imread('woodright.jpg')
w = wood_left.shape[1]
h = wood_left.shape[0]
fps_time = time()
while True:
if left:
scr = numpy.array(sct.grab(dimensions_left))
wood = wood_left
else:
scr = numpy.array(sct.grab(dimensions_right))
wood = wood_right
# Cut off alpha
scr_remove = scr[:,:,:3]
# Tag:需要注意就是img size必须小于template.
result = cv2.matchTemplate(scr_remove, wood, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
print(f"Max Val: {max_val} Max Loc: {max_loc}")
src = scr.copy()
if max_val > MATCHING_TH:
# if max_val > .85:
if left:
# x=340
x=JUMP_RIGHT[0]
y=JUMP_RIGHT[1]
print("trun right")
else:
x=JUMP_LEFT[0]
y=JUMP_LEFT[1]
left = not left
pyautogui.click(x=x, y=y)
# 0.1s不行, 运行有点问题.
# sleep(.10)
sleep(KICKING_TIME)
if keyboard.is_pressed('q'):
break
print('FPS: {}'.format(1 / (time() - fps_time)))
fps_time = time()
标签:JUMP,--,cv2,chop,wood,time,left,vision,scr 来源: https://blog.csdn.net/sinat_20276189/article/details/121788341