-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEvaluator.py
267 lines (192 loc) · 8.45 KB
/
Evaluator.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import requests, traceback, time
import config as c
from PieceMasks import *
from colors import *
from numpy import ndarray
from TetrisUtility import lineClear, pieceOnBoard, getPlacementStr
import AnalysisConstants as AC
from multiprocessing.dummy import Pool as ThreadPool
import Evaluator
def getInfo(position):
x_and_dots = c.hzString
def toStr(arr):
return "".join(map(str,arr.ravel().astype(int)))
b1Str = toStr(position.board)
if type(position.placement) != ndarray:
b2Str = None
else:
b2Str = toStr(lineClear(position.board + position.placement)[0])
currStr = TETRONIMO_LETTER[position.currentPiece]
nextStr = TETRONIMO_LETTER[position.nextPiece]
if c.gamemode == c.PAL:
if position.level >= 19:
level = 29
lines = 0
elif 16 <= position.level <= 18:
level = 19
lines = 0
else:
level = 18
lines = 0
if position.level <= 12:
x_and_dots = TIMELINE_MAX_HZ
else:
# API calls only work for 18/19/29 starts. Need to do manual conversion for lower starts.
if c.startLevel >= 18 or position.level >= 29:
level = position.level
lines = position.lines
else: # NTSC only
if position.level <= 19:
lines = 0
level = 19 if position.level == 19 else 18
elif position.level <= 27:
lines = 0
level = 19
else: # position.level == 28
lines = 220 + position.lines % 10
level = 28
# For levels lower than 18 speeds, just assume 30hz movement (unlimited piece range)
if position.level < 16:
x_and_dots = TIMELINE_MAX_HZ
return [b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots]
# Given current position, generate analysis from StackRabbit call
def evaluate(position):
if not c.isAnalysis:
print("exit")
return
number = position.id
print("Start eval ", number)
t = time.time()
assert(position.nextPiece is not None)
assert(type(position.placement) == ndarray)
try:
b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots = getInfo(position)
result = makeAPICallEvaluation(b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots)
print("Finish eval ", number, time.time() - t)
position.setEvaluation(*result)
print("Set eval ", number)
with c.lock:
c.numEvalDone += 1
except Exception as e:
traceback.print_exc()
print(number, e, type(e))
def getJson(url):
# try request up to 3 times for internet connection things
tries = 10
for i in range(tries):
try:
if c.session == None:
return requests.get(url).json()
else:
return c.session.get(url).json()
except:
print("Internet connection attempt {}/{} failed.".format(i+1,tries))
print("Failed to establish API response. URL was {}".format(url))
def printData(position):
b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots = getInfo(position)
url = "https://stackrabbit.herokuapp.com/engine-movelist?board={}¤tPiece={}&nextPiece={}&level={}&lines={}&inputFrameTimeline={}"
url = url.format(b1Str, currStr, nextStr, level, lines, x_and_dots)
print(url)
url = "https://stackrabbit.herokuapp.com/rate-move?board={}&secondBoard={}¤tPiece={}&nextPiece={}&level={}&lines={}&inputFrameTimeline={}"
url = url.format(b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots)
print(url)
def generateHypotheticalLines(depth3):
text = []
colors = []
values = []
for line in depth3:
try:
piece, prob, pos, val = LETTER_TO_PIECE[line["pieceSequence"]], round(100*line["probability"]), line["moveSequence"][0], round(line["resultingValue"],1)
colors.append(BLACK)
values.append(val)
placement = pieceOnBoard(piece, *pos)
string = getPlacementStr(placement, piece)
text.append("If {} ({}%), do {} = {}".format(TETRONIMO_LETTER[piece], prob, string, val))
except:
print(line)
traceback.print_exc()
lowIndex = 0
highIndex = 0
for i in range(len(values)):
if values[i] < values[lowIndex]:
lowIndex = i
if values[i] > values[highIndex]:
highIndex = i
colors[lowIndex] = AC.C_BLUN
colors[highIndex] = AC.C_BEST
return text, colors
# return a formatted list based on eval explanation text
def parseExplanation(text):
text = text[:text.index(", \nSUBTOTAL")]
result = ["","Eval Factors:"]
result.extend(text.split(", "))
return result
def makeAPICallPossible(position):
if not c.isAnalysis:
print("exit")
return
print("Start possible ", position.id)
b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots = getInfo(position)
# API call for possible moves
url = "https://stackrabbit.herokuapp.com/engine-movelist?board={}¤tPiece={}&nextPiece={}&level={}&lines={}&inputFrameTimeline={}"
url2 = "https://stackrabbit.herokuapp.com/engine-movelist?board={}¤tPiece={}&level={}&lines={}&inputFrameTimeline={}"
url = url.format(b1Str, currStr, nextStr, level, lines, x_and_dots)
url2 = url2.format(b1Str, currStr, level, lines, x_and_dots)
print(url)
json = getJson(url)
nnb = getJson(url2)[0]
# Parse best NNB move data
text, _ = generateHypotheticalLines(nnb["hypotheticalLines"])
text.extend(parseExplanation(nnb["evalExplanation"]))
position.setNNB(float(nnb["totalValue"]), pieceOnBoard(position.currentPiece, *nnb["placement"]), position.currentPiece, text)
# Parse NB movelist data
i = 0
for data in json:
if i == 5:
break
currData = data[0]
nextData = data[1]
currMask = pieceOnBoard(position.currentPiece, *currData["placement"])
nextMask = pieceOnBoard(position.nextPiece, *nextData["placement"])
text, colors = generateHypotheticalLines(nextData["hypotheticalLines"])
text2 = parseExplanation(currData["evalExplanation"])
text.extend(text2)
colors.extend([BLACK]*len(text2))
unique = position.addPossible(float(currData["totalValue"]), currMask, nextMask, position.currentPiece, position.nextPiece, text, colors)
if unique:
i += 1
print("Finish possible ", position.id)
with c.lock:
c.possibleCount += 1
def makeAPICallEvaluation(b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots):
depth = "1" if c.isEvalDepth3 else "0"
# API call for evaluations
url = "https://stackrabbit.herokuapp.com/rate-move?board={}&secondBoard={}¤tPiece={}&nextPiece={}&level={}&lines={}&inputFrameTimeline={}&lookaheadDepth={}"
url = url.format(b1Str, b2Str, currStr, nextStr, level, lines, x_and_dots, depth)
print(url)
json = getJson(url)
isFailed = False
if json is not None:
playerNNB, playerFinal, bestNNB, bestFinal = json['playerMoveNoAdjustment'], json['playerMoveAfterAdjustment'], float(json['bestMoveNoAdjustment']), float(json['bestMoveAfterAdjustment'])
else:
playerNNB, playerFinal, bestNNB, bestFinal = -1,-1,-1,-1
isFailed = True
try: # The player move is found in SF
playerNNB = float(playerNNB)
playerFinal = float(playerFinal)
rapid = False
except: # Player made a move faster than inputted hz. In this case, compare with 30hz StackRabbit and determine whether "rather rapid" should be awarded
#print("rapid")
url = "https://stackrabbit.herokuapp.com/rate-move?board={}&secondBoard={}¤tPiece={}&nextPiece={}&level={}&lines={}&inputFrameTimeline={}&lookaheadDepth={}"
url = url.format(b1Str, b2Str, currStr, nextStr, level, lines, TIMELINE_MAX_HZ, depth)
print("url 2 ", url)
json = getJson(url)
try:
playerNNB, playerFinal = float(json['playerMoveNoAdjustment']), float(json['playerMoveAfterAdjustment'])
rapid = True
except:
playerNNB, playerFinal = -1, -1
isFailed = True
rapid = False
print("Error: ", url)
return playerNNB, playerFinal, bestNNB, bestFinal, rapid, url, isFailed