我找到了一种使用 Imagegrab 和 ImageStat 通过 PIL 执行此操作的方法。这是抓取屏幕并裁剪到游戏窗口:
def getScreen():
# Grab image and crop it to the desired window. Find pixel borders manually.
box = (left, top, right, bottom)
im = ImageGrab.grab().crop(box)
#im.save('testcrop.jpg') # optionally save your crop
for y in reversed(range(8)):
for x in reversed(range(8)):
#sqh,sqw are the height and width of each piece.
#each pieceim is one of the game piece squares
piecebox = ( sqw*(x), sqh*(y), sqw*(x+1), sqh*(y+1))
pieceim = im.crop(piecebox)
#pieceim.save('piececrop_xy_'+ str(x) + str(y) + '.jpg')
stats = ImageStat.Stat(pieceim)
statsmean = stats.mean
Rows[x][y] = whichpiece(statsmean)
上面为所有 64 个片段创建了一个图像,识别片段类型,并将其存储在数组“行”的数组中。然后,我使用 stats.mean 为每个片段类型获取平均 RGB 值,并将它们存储在字典 (rgbdict) 中。将所有输出复制到 Excel 中并按颜色类型过滤以获得这些平均值。然后我使用 RSS 方法和该字典将图像与已知的片段类型进行统计匹配。 (RSS 参考:http://www.charlesrcook.com/archive/2010/09/05/creating-a-bejeweled-blitz-bot-in-c.aspx)
rgbdict = {
'blue':[65.48478993, 149.0030965, 179.4636593], #1
'red':[105.3613444,55.95710092, 36.07481793], #2
......
}
def whichpiece(statsmean):
bestScore = 100
curScore= 0
pieceColor = 'empty'
for key in rgbdict.keys():
curScore = (math.pow( (statsmean[0]/255) - (rgbdict[key][0]/255), 2)
+ math.pow( (statsmean[1]/255) - (rgbdict[key][1]/255), 2)
+ math.pow( (statsmean[2]/255) - (rgbdict[key][2]/255), 2) )
if curScore < bestScore:
pieceColor = key
bestScore = curScore
return piececolor
通过这两个功能,可以刮屏,并将棋盘状态转移到可以决定移动的数组中。如果这对任何人有帮助,祝你好运,如果你微调了移动选择器,请告诉我。