-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.py
188 lines (183 loc) · 8.7 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import sys
import copy
import queue
import os
import shutil
from PIL import Image, ImageDraw
import imageio
from basic import StoneType
import config as cfg
def analyze(_initBoard):
# determine where to start
q = queue.PriorityQueue()
minCost, bestRowIdx, bestColIdx = 10e9, 0, 0
# try every possible stone
for rowIdx in range(_initBoard.numOfRows):
for colIdx in range(_initBoard.numOfCols):
_initBoard.setCurrentPosition([rowIdx, colIdx])
cost, count, moveList = 10e9, 0, []
q.put( (cost, count, moveList, _initBoard) )
while not q.empty():
(cost, _, moveList, board) = q.get()
if cost < minCost:
minCost, bestRowIdx, bestColIdx = (cost, rowIdx, colIdx)
if len(moveList) >= 5:
continue
for successorIdx, successor in enumerate( board.getSuccessorList() ):
count = count + 1
(newBoard, move) = successor
stones, boundary, combo, end = newBoard.evaluate()
newCost = -(combo * 100 + boundary * 50 + stones) + len(moveList) * 0.001
newCost = newCost + 100 if end else newCost
newMoveList = copy.copy(moveList)
newMoveList.append(move)
q.put( (newCost, count, newMoveList, newBoard) )
# search end - set current position to the best position
_initBoard.setCurrentPosition([bestRowIdx, bestColIdx])
stones, boundary, combo, end = _initBoard.evaluate()
sys.stderr.write(str(_initBoard) + "\n")
# search best result
q = queue.PriorityQueue()
cost, count, moveList = 10e9, 0, []
minCost, bestMoveList, bestBoard = (cost, moveList, _initBoard)
numOfPhases, finalMoveList = 5, []
# break the search mechanism into several phases
for it in range(1, numOfPhases + 1):
q.put( (minCost, count, bestMoveList, bestBoard) )
# bfs with evaluation as reward
while not q.empty():
(cost, _, moveList, board) = q.get()
if cost < minCost:
minCost, bestMoveList, bestBoard = (cost, moveList, board)
if len(moveList) >= 10:
continue
for successorIdx, successor in enumerate( board.getSuccessorList() ):
count = count + 1
(newBoard, move) = successor
stones, boundary, combo, end = newBoard.evaluate()
newCost = -(combo * 100 + boundary * 10 * (numOfPhases - it) + stones) + len(moveList) * 0.001
newCost = newCost + 100 if end and it != numOfPhases else newCost
newMoveList = copy.copy(moveList)
newMoveList.append(move)
q.put( (newCost, count, newMoveList, newBoard) )
# end search - concatenate the move list and evaluate again
stones, boundary, combo, end = bestBoard.evaluate()
minCost = -(combo * 100 + boundary * 10 * (numOfPhases - 1 - it) + stones)
minCost = minCost + 100 if end and it != (numOfPhases - 1) else minCost
finalMoveList = finalMoveList + bestMoveList
bestMoveList = []
sys.stderr.write( "phase {}/{}\n".format(it, numOfPhases) )
sys.stderr.write( "stones={}, boundary={}, combo={}, end={}, steps={}, count={}\n".format(stones, boundary, combo, end, len(finalMoveList), count) )
sys.stderr.write(str(bestBoard) + "\n")
# return final result
return bestBoard, finalMoveList
def drawBoard(_board):
pixels = cfg.settings["pixels"]
type2Foreground = {
StoneType.DARK: Image.open(cfg.imagePath["dark"]).convert("RGBA"),
StoneType.LIGHT: Image.open(cfg.imagePath["light"]).convert("RGBA"),
StoneType.WATER: Image.open(cfg.imagePath["water"]).convert("RGBA"),
StoneType.FIRE: Image.open(cfg.imagePath["fire"]).convert("RGBA"),
StoneType.EARTH: Image.open(cfg.imagePath["earth"]).convert("RGBA"),
StoneType.HEALTH: Image.open(cfg.imagePath["health"]).convert("RGBA")
}
background = Image.open(cfg.imagePath["background"]).convert("RGBA")
for rowIdx in range(_board.numOfRows):
for colIdx in range(_board.numOfCols):
stone = _board.runestones[rowIdx][colIdx]
foreground = type2Foreground[stone.type]
location = (colIdx * pixels, rowIdx * pixels)
background.paste(foreground, location, foreground)
return background
def visualizePath(_initBoard, _bestBoard, _finalMoveList):
# create directory
if os.path.exists(cfg.outputDir):
shutil.rmtree(cfg.outputDir)
os.makedirs(cfg.outputDir)
# setup image objects
hand = Image.open(cfg.imagePath["hand"]).convert("RGBA")
flag = Image.open(cfg.imagePath["flag"]).convert("RGBA")
# init draw settings
pixels = cfg.settings["pixels"]
lineWidth = cfg.settings["lineWidth"]
lineColor = cfg.settings["lineColor"]
# draw init and best board
drawBoard(_initBoard).save( os.path.join(cfg.outputDir, "initBoard.png") )
drawBoard(_bestBoard).save( os.path.join(cfg.outputDir, "bestBoard.png") )
# draw path images
board = _initBoard
path = drawBoard(_initBoard)
d = ImageDraw.Draw(path)
delta, pathIdx, visited = pixels // 2, 1, [board.previousPosition]
for finalMoveIdx, finalMove in enumerate(_finalMoveList):
oldBoard = board
for successorIdx, successor in enumerate( oldBoard.getSuccessorList() ):
(newBoard, move) = successor
board = newBoard if finalMove == move else board
if board.currentPosition in visited:
# draw start and end before saving
path.paste(hand, (visited[0][1] * pixels, visited[0][0] * pixels), hand)
path.paste(flag, (board.previousPosition[1] * pixels, board.previousPosition[0] * pixels), flag)
path.save( os.path.join( cfg.outputDir, "path{:0>2d}.png".format(pathIdx) ) )
# create new path image
path = drawBoard(oldBoard)
d = ImageDraw.Draw(path)
pathIdx, visited = pathIdx + 1, [board.previousPosition]
src = (board.previousPosition[1] * pixels + delta, board.previousPosition[0] * pixels + delta)
des = (board.currentPosition[1] * pixels + delta, board.currentPosition[0] * pixels + delta)
d.line([src, des], fill = lineColor, width = lineWidth)
visited.append(board.currentPosition)
path.paste(hand, (visited[0][1] * pixels, visited[0][0] * pixels), hand)
path.paste(flag, (board.currentPosition[1] * pixels, board.currentPosition[0] * pixels), flag)
path.save( os.path.join( cfg.outputDir, "path{:0>2d}.png".format(pathIdx) ) )
# gif
images = [imageio.imread( os.path.join(cfg.outputDir, "initBoard.png") )]
for idx in range(1, pathIdx + 1):
images.append( imageio.imread( os.path.join( cfg.outputDir, "path{:0>2d}.png".format(idx) ) ) )
images.append( imageio.imread( os.path.join(cfg.outputDir, "bestBoard.png") ) )
imageio.mimsave(os.path.join(cfg.outputDir, "path.gif"), images, duration = 1.5)
def screenshotToTypes(_filePath, _numOfRows, _numOfCols):
# load image and config
screen = Image.open(_filePath).convert("RGB")
pixels = cfg.settings["pixels"]
width = screen.size[0]
height = int(width * 1.5)
delta = (screen.size[1] - height) // 2
box = (0, screen.size[1] - delta - width // _numOfCols * _numOfRows, width, screen.size[1] - delta)
screen = screen.crop(box).resize( (pixels * _numOfCols, pixels * _numOfRows), Image.BILINEAR )
# init
types = list()
type2Value = {
StoneType.DARK: (118, 28, 138),
StoneType.LIGHT: (120, 89, 11),
StoneType.WATER: (44, 90, 136),
StoneType.FIRE: (153, 28, 15),
StoneType.EARTH: (27, 117, 31),
StoneType.HEALTH: (172, 74, 128)
}
type2Weight = {
StoneType.DARK: 1.0,
StoneType.LIGHT: 1.0,
StoneType.WATER: 1.0,
StoneType.FIRE: 1.0,
StoneType.EARTH: 1.0,
StoneType.HEALTH: 1.7
}
# parse
for rowIdx in range(_numOfRows):
types.append( list() )
for colIdx in range(_numOfCols):
types[rowIdx].append(None)
box = (colIdx * pixels, rowIdx * pixels, (colIdx + 1) * pixels, (rowIdx + 1) * pixels)
value = screen.crop(box).resize( (1, 1), Image.ANTIALIAS ).getpixel( (0, 0) )
minDist = 10e9
for t in type2Value:
v = type2Value[t]
dist = abs(value[0] - v[0]) + abs(value[1] - v[1]) + abs(value[2] - v[2])
dist = dist * type2Weight[t]
if dist >= minDist:
continue
minDist = dist
types[rowIdx][colIdx] = t
# return types
return types