-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai.py
299 lines (221 loc) · 6.84 KB
/
ai.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
from pykeyboard import PyKeyboard
from tetris.__Main__ import Main
import time
import copy
from random import randint
from threading import Thread
class AI:
def __init__(self, LINES_CLEARED_MULTIPLIER, AGGREGATE_HEIGHT_MULTIPLIER, HOLES_MULTIPLIER, BUMPINESS_MULTIPLIER):
self.linesClearedMult = LINES_CLEARED_MULTIPLIER
self.agHeightMult = AGGREGATE_HEIGHT_MULTIPLIER
self.holesMult = HOLES_MULTIPLIER
self.bumpinessMult = BUMPINESS_MULTIPLIER
self.keyboard = PyKeyboard()
self.tetris = Main()
def quit(self):
self.keyboard.tap_key('q')
time.sleep(1)
self.keyboard.tap_key('y')
def pause(self):
self.keyboard.tap_key('p')
def runAI(self):
gameThread = Thread(target=self.runTetris)
gameThread.start()
time.sleep(1)
self.keyboard.press_key('s')
#Game loop
while not self.tetris.g.gameOver:
#Wait while next piece is loading
while self.tetris.g.currPiece is None:
time.sleep(0.05)
time.sleep(0.05)
moveToExecute = self.calculateMove()
self.executeMove(moveToExecute)
self.keyboard.tap_key('Down')
time.sleep(2)
self.keyboard.tap_key('n')
def calculateMove(self):
#First save game state and copy board and piece
testingGame = copy.deepcopy(self.tetris.g)
savedGameState = copy.deepcopy(self.tetris.g)
possibleMoves = self.getAllPrimaryAndSecondaryMoves(testingGame)
self.tetris.g = savedGameState
bestMove = self.calculateBestMove(possibleMoves)
return bestMove
def getAllPrimaryAndSecondaryMoves(self, game):
primaryMoves = self.getAllPossibleMoves(game)
subMoveGame = copy.deepcopy(game)
for move in primaryMoves:
# Get all possible moves for the next piece, given the previous move
subMoveGame = copy.deepcopy(game)
subMoveGame.board = move['board']
subMoveGame.newPiece()
subMoves = self.getAllPossibleMoves(subMoveGame)
move['subMoves'] = subMoves
# Each Primary move contains a list of submoves
return primaryMoves
def getAllPossibleMoves(self, game):
moves = []
#First Position furthest left possible
#Then drop from every possible column with every possible rotation
firstRotation = True
startingRotation = game.currPiece.currRotation
#For every rotation position
while game.currPiece.currRotation != startingRotation or firstRotation:
firstShift = True
firstRotation = False
self.positionFurthestLeft(game)
oldCol = game.currPiece.topLeft.col
#For every col
while game.currPiece.topLeft.col != oldCol or firstShift:
beforeShift = copy.deepcopy(game)
firstShift= False
oldCol = game.currPiece.topLeft.col
self.dropPiece(game, game.board)
landingStats = {}
#Calculate all board combos with the next piece
landingStats['rotationIndex'] = game.currPiece.currRotation
landingStats['topLeftCol'] = game.currPiece.topLeft.col
landingStats['topLeftRow'] = game.currPiece.topLeft.row
landingStats['board'] = game.board
moves.append(landingStats)
game = beforeShift
game.movePiece(1)
game.rotatePiece()
return moves
def positionFurthestLeft(self, game):
for x in range(10):
game.movePiece(-1)
def dropPiece(self, game, board):
while not game.fallPiece():
game.fallPiece()
game.landPiece(False)
game.updateBoard()
def calculateBestMove(self, moves):
scoreToMove = {}
for move in moves:
score = self.calculateMoveScore(move)
maxSubScore = 0
for subMove in move['subMoves']:
subScore = self.calculateMoveScore(move)
if subScore > maxSubScore:
maxSubScore = subScore
#add the score and it's best subScore
score += maxSubScore
scoreToMove[score] = move
maxScore = 0
for score in scoreToMove:
if score > maxScore:
maxScore = score
selectedMove = scoreToMove[maxScore]
selectedMove.pop('board')
return selectedMove
def calculateMoveScore(self, move):
lines = self.calculateLinesMade(move['board'])
result = self.calculateAggregateHeightAndBumpiness(move['board'])
agHeight = result[0]
bumpiness = result[1]
holes = self.calculateHoles(move['board'])
score = (lines * self.linesClearedMult) + (agHeight * self.agHeightMult) \
+ (holes * self.holesMult) + (bumpiness * self.bumpinessMult) + 1000
if score < 0:
score = 0
return score
def calculateLinesMade(self, board):
lines = 0
rows = range(len(board))
columns = range(len(board[0]))
for r in rows:
linePresent = True
for c in columns:
if board[r][c] == 0:
linePresent = False
break
if linePresent:
lines = lines + 1
return lines
def calculateAggregateHeightAndBumpiness(self, board):
rows = range(len(board))
columns = range(len(board[0]))
aggregateHeight = 0
columnHeight = 0
bumpiness = 0
first = True
for c in reversed(columns):
previousHeight = columnHeight
reachedEmpty = False
columnHeight = 23
for r in reversed(rows):
if reachedEmpty and board[r][c] != 0:
reachedEmpty = False
if board[r][c] == 0 and not reachedEmpty:
reachedEmpty = True
columnHeight = 23 - (r+1)
if not first:
bumpyDelta = abs(previousHeight - columnHeight)
bumpiness = bumpiness + bumpyDelta
aggregateHeight = aggregateHeight + columnHeight
if first:
aggregateHeight = aggregateHeight + columnHeight
first = False
result = []
result.append(aggregateHeight)
result.append(bumpiness)
return result
def calculateHoles(self, board):
rows = range(len(board))
columns = range(len(board[0]))
holes = 0
for r in reversed(rows):
empty = True
for c in reversed(columns):
if board[r][c] != 0:
empty = False
elif board[r][c] == 0:
for searchRow in reversed(range(0,r)):
if board[searchRow][c] != 0:
holes = holes + 1
break
if empty:
return holes
return holes
def executeMove(self, move):
start = time.time()
sleepTime = 0.2
if self.tetris.g.currPiece.topLeft.col < move['topLeftCol']:
direction = 'Right'
else:
direction = 'Left'
while self.tetris.g.currPiece.currRotation != move['rotationIndex']:
if time.time() >= start + 5:
return
if self.tetris.g.gameOver:
return
self.keyboard.tap_key('Up')
time.sleep(sleepTime)
while self.tetris.g.currPiece.topLeft.col != move['topLeftCol']:
if time.time() >= start + 5:
return
if self.tetris.g.gameOver:
return
self.keyboard.tap_key(direction)
time.sleep(sleepTime)
while self.tetris.g.currPiece.topLeft.row < move['topLeftRow'] - 1:
if time.time() >= start + 5:
return
if self.tetris.g.gameOver:
return
self.keyboard.tap_key('Down')
time.sleep(sleepTime/2)
def runTetris(self):
try:
self.tetris.doWelcome()
self.tetris.gameLoop()
except ZeroDivisionError as e:
pass
except KeyboardInterrupt as e:
pass
except Exception as e:
raise e
finally:
self.tetris.doFinish()