forked from nuno-faria/tetris-ai
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtetris.py
344 lines (295 loc) · 11.5 KB
/
tetris.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import random
from typing import Dict, List, Tuple
import cv2
import numpy as np
import itertools
from PIL import Image
# Tetris game class
# noinspection PyMethodMayBeStatic
class Tetris:
"""Tetris game class"""
# BOARD
MAP_EMPTY = 0
MAP_BLOCK = 1
MAP_PLAYER = 2
BOARD_WIDTH = 10
BOARD_HEIGHT = 20
TETROMINOS = {
0: { # I
0: [(0, 0), (1, 0), (2, 0), (3, 0)],
90: [(1, 0), (1, 1), (1, 2), (1, 3)],
180: [(3, 0), (2, 0), (1, 0), (0, 0)],
270: [(1, 3), (1, 2), (1, 1), (1, 0)],
},
1: { # T
0: [(1, 0), (0, 1), (1, 1), (2, 1)],
90: [(0, 1), (1, 2), (1, 1), (1, 0)],
180: [(1, 2), (2, 1), (1, 1), (0, 1)],
270: [(2, 1), (1, 0), (1, 1), (1, 2)],
},
2: { # L
0: [(1, 0), (1, 1), (1, 2), (2, 2)],
90: [(0, 1), (1, 1), (2, 1), (2, 0)],
180: [(1, 2), (1, 1), (1, 0), (0, 0)],
270: [(2, 1), (1, 1), (0, 1), (0, 2)],
},
3: { # J
0: [(1, 0), (1, 1), (1, 2), (0, 2)],
90: [(0, 1), (1, 1), (2, 1), (2, 2)],
180: [(1, 2), (1, 1), (1, 0), (2, 0)],
270: [(2, 1), (1, 1), (0, 1), (0, 0)],
},
4: { # Z
0: [(0, 0), (1, 0), (1, 1), (2, 1)],
90: [(0, 2), (0, 1), (1, 1), (1, 0)],
180: [(2, 1), (1, 1), (1, 0), (0, 0)],
270: [(1, 0), (1, 1), (0, 1), (0, 2)],
},
5: { # S
0: [(2, 0), (1, 0), (1, 1), (0, 1)],
90: [(0, 0), (0, 1), (1, 1), (1, 2)],
180: [(0, 1), (1, 1), (1, 0), (2, 0)],
270: [(1, 2), (1, 1), (0, 1), (0, 0)],
},
6: { # O
0: [(1, 0), (2, 0), (1, 1), (2, 1)],
90: [(1, 0), (2, 0), (1, 1), (2, 1)],
180: [(1, 0), (2, 0), (1, 1), (2, 1)],
270: [(1, 0), (2, 0), (1, 1), (2, 1)],
}
}
COLORS = {
0: (255, 255, 255),
1: (247, 64, 99),
2: (0, 167, 247),
}
def __init__(self):
# to avoid warnings just mention the warnings
self.game_over = False
self.current_pos = [3, 0]
self.current_rotation = 0
self.board = []
self.bag = []
self.next_piece = None
self.score = 0
self.reset()
def reset(self):
"""Resets the game, returning the current state"""
self.board = [[0] * Tetris.BOARD_WIDTH for _ in range(Tetris.BOARD_HEIGHT)]
self.game_over = False
self.bag = list(range(len(Tetris.TETROMINOS)))
random.shuffle(self.bag)
self.next_piece = self.bag.pop()
self._new_round(piece_fall=False)
self.score = 0
return self._get_board_props(self.board)
def _get_rotated_piece(self, rotation):
"""Returns the current piece, including rotation"""
return Tetris.TETROMINOS[self.current_piece][rotation]
def _get_complete_board(self):
"""Returns the complete board, including the current piece"""
piece = self._get_rotated_piece(self.current_rotation)
piece = [np.add(x, self.current_pos) for x in piece]
board = [x[:] for x in self.board]
for x, y in piece:
board[y][x] = Tetris.MAP_PLAYER
return board
def get_game_score(self):
"""Returns the current game score.
Each block placed counts as one.
For lines cleared, it is used BOARD_WIDTH * lines_cleared ^ 2.
"""
return self.score
def _new_round(self, piece_fall=False) -> int:
"""Starts a new round (new piece)"""
score = 0
if piece_fall:
# Update board and calculate score
piece = self._get_rotated_piece(self.current_rotation)
self.board = self._add_piece_to_board(piece, self.current_pos)
lines_cleared, self.board = self._clear_lines(self.board)
score = 1 + (lines_cleared ** 2) * Tetris.BOARD_WIDTH
self.score += score
# Generate new bag with the pieces
if len(self.bag) == 0:
self.bag = list(range(len(Tetris.TETROMINOS)))
random.shuffle(self.bag)
self.current_piece = self.next_piece
self.next_piece = self.bag.pop()
self.current_pos = [3, 0]
self.current_rotation = 0
if not self.is_valid_position(self._get_rotated_piece(self.current_rotation), self.current_pos):
self.game_over = True
return score
def is_valid_position(self, piece, pos):
"""Check if there is a collision between the current piece and the board.
:returns: True, if the piece position is _invalid_, False, otherwise
"""
for x, y in piece:
x += pos[0]
y += pos[1]
if x < 0 or x >= Tetris.BOARD_WIDTH \
or y < 0 or y >= Tetris.BOARD_HEIGHT \
or self.board[y][x] == Tetris.MAP_BLOCK:
return False
return True
def _rotate(self, angle):
"""Change the current rotation"""
r = self.current_rotation + angle
if r == 360:
r = 0
if r < 0:
r += 360
elif r > 360:
r -= 360
self.current_rotation = r
def _add_piece_to_board(self, piece, pos):
"""Place a piece in the board, returning the resulting board"""
board = [x[:] for x in self.board]
for x, y in piece:
board[y + pos[1]][x + pos[0]] = Tetris.MAP_BLOCK
return board
def _clear_lines(self, board):
"""Clears completed lines in a board"""
# Check if lines can be cleared
lines_to_clear = [index for index, row in enumerate(board) if sum(row) == Tetris.BOARD_WIDTH]
if lines_to_clear:
board = [row for index, row in enumerate(board) if index not in lines_to_clear]
# Add new lines at the top
for _ in lines_to_clear:
board.insert(0, [0 for _ in range(Tetris.BOARD_WIDTH)])
return len(lines_to_clear), board
def _number_of_holes(self, board):
"""Number of holes in the board (empty square with at least one block above it)"""
holes = 0
for col in zip(*board):
tail = itertools.dropwhile(lambda x: x != Tetris.MAP_BLOCK, col)
holes += len([x for x in tail if x == Tetris.MAP_EMPTY])
return holes
def _bumpiness(self, board):
"""Sum of the differences of heights between pair of columns"""
total_bumpiness = 0
max_bumpiness = 0
min_ys = []
for col in zip(*board):
tail = itertools.dropwhile(lambda x: x != Tetris.MAP_BLOCK, col)
n = Tetris.BOARD_HEIGHT - len([x for x in tail])
min_ys.append(n)
for (y0, y1) in window(min_ys):
bumpiness = abs(y0 - y1)
max_bumpiness = max(bumpiness, max_bumpiness)
total_bumpiness += bumpiness
return total_bumpiness, max_bumpiness
def _height(self, board):
"""Sum and maximum height of the board"""
sum_height = 0
max_height = 0
min_height = Tetris.BOARD_HEIGHT
for col in zip(*board):
tail = itertools.dropwhile(lambda x: x != Tetris.MAP_BLOCK, col)
height = len([x for x in tail])
sum_height += height
max_height = max(height, max_height)
min_height = min(height, min_height)
return sum_height, max_height, min_height
def _get_board_props(self, board) -> List[int]:
"""Get properties of the board"""
lines, board = self._clear_lines(board)
holes = self._number_of_holes(board)
total_bumpiness, max_bumpiness = self._bumpiness(board)
sum_height, max_height, min_height = self._height(board)
return [lines, holes, total_bumpiness, sum_height]
def get_next_states(self) -> Dict[Tuple[int, int], List[int]]:
"""Get all possible next states"""
states = {}
piece_id = self.current_piece
if piece_id == 6:
rotations = [0]
elif piece_id == 0:
rotations = [0, 90]
else:
rotations = [0, 90, 180, 270]
# For all rotations
for rotation in rotations:
piece = Tetris.TETROMINOS[piece_id][rotation]
min_x = min([p[0] for p in piece])
max_x = max([p[0] for p in piece])
# For all positions
for x in range(-min_x, Tetris.BOARD_WIDTH - max_x):
pos = [x, 0]
# Drop piece
while self.is_valid_position(piece, pos):
pos[1] += 1
pos[1] -= 1
# Valid move
if pos[1] >= 0:
board = self._add_piece_to_board(piece, pos)
states[(x, rotation)] = self._get_board_props(board)
return states
def get_state_size(self):
"""Size of the state"""
return 4
def move(self, shift_m, shift_r) -> bool:
pos = self.current_pos.copy()
pos[0] += shift_m[0]
pos[1] += shift_m[1]
rotation = self.current_rotation
rotation = (rotation + shift_r + 360) % 360
piece = self._get_rotated_piece(rotation)
if self.is_valid_position(piece, pos):
self.current_pos = pos
self.current_rotation = rotation
return True
return False
def fall(self) -> bool:
""":returns: True, if there was a fall move, False otherwise"""
if not self.move([0, 1], 0):
# cannot fall further
# start new round
self._new_round(piece_fall=True)
if self.game_over:
self.score -= 2
return self.game_over
def hard_drop(self, pos, rotation, render=False):
"""Makes a hard drop given a position and a rotation, returning the reward and if the game is over"""
self.current_pos = pos
self.current_rotation = rotation
# drop piece
piece = self._get_rotated_piece(self.current_rotation)
while self.is_valid_position(piece, self.current_pos):
if render:
self.render(wait_key=True)
self.current_pos[1] += 1
self.current_pos[1] -= 1
# start new round
score = self._new_round(piece_fall=True)
if self.game_over:
score -= 2
if render:
self.render(wait_key=True)
return score, self.game_over
def render(self, wait_key=False):
"""Renders the current board"""
img = [Tetris.COLORS[p] for row in self._get_complete_board() for p in row]
img = np.array(img).reshape((Tetris.BOARD_HEIGHT, Tetris.BOARD_WIDTH, 3)).astype(np.uint8)
img = img[..., ::-1] # Convert RRG to BGR (used by cv2)
img = Image.fromarray(img, 'RGB')
img = img.resize((Tetris.BOARD_WIDTH * 25, Tetris.BOARD_HEIGHT * 25))
img = np.array(img)
cv2.putText(img, str(self.score), (22, 22), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 1)
cv2.imshow('image', np.array(img))
if wait_key:
# this is needed to render during training
cv2.waitKey(1)
def window(seq, n=2):
"""Returns a sliding window (of width n) over data from the iterable
s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
NB. taken from https://docs.python.org/release/2.3.5/lib/itertools-example.html
"""
it = iter(seq)
result = tuple(itertools.islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result