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
|
#!/usr/bin/env python3
import contextlib
import random
import sys
import time
import pygame
class WouldCollide(Exception):
pass
class Piece():
def rotate(self):
pass
def rotate_clockwise(self):
self.rotate()
def rotate_counter_clockwise(self):
self.rotate()
class ZPiece(Piece):
def __init__(self):
self.elements = (blue_square, blue_square, None), (None, blue_square, blue_square), (None, None, None)
self.vertical = False
def rotate(self):
if self.vertical:
self.elements = (blue_square, blue_square, None), (None, blue_square, blue_square), (None, None, None)
else:
self.elements = (None, None, blue_square), (None, blue_square, blue_square), (None, blue_square, None)
self.vertical = not self.vertical
class SPiece(Piece):
def __init__(self):
self.elements = (None, None, None), (None, green_square, green_square), (green_square, green_square, None)
self.vertical = False
def rotate(self):
if self.vertical:
self.elements = (None, green_square, green_square), (green_square, green_square, None), (None, None, None)
else:
self.elements = (None, green_square, None), (None, green_square, green_square), (None, None, green_square)
self.vertical = not self.vertical
class SquarePiece(Piece):
def __init__(self):
self.elements = ((white_square, white_square), (white_square, white_square))
class IPiece(Piece):
def __init__(self):
self.elements = (None, None, None, None), (None, None, None, None), (red_square, red_square, red_square, red_square), (None, None, None, None)
self.vertical = False
def rotate(self):
if self.vertical:
self.elements = (None, None, None, None), (None, None, None, None), (red_square, red_square, red_square, red_square), (None, None, None, None)
else:
self.elements = (None, None, red_square, None), (None, None, red_square, None), (None, None, red_square, None), (None, None, red_square, None)
self.vertical = not self.vertical
class TPiece(Piece):
def __init__(self):
self.elements = [[yellow_square, yellow_square, yellow_square], [None, yellow_square, None], [None, None, None]]
def rotate_clockwise(self):
# Set the corners
self.elements[0][0], self.elements[0][2], self.elements[2][2], self.elements[2][0] = self.elements[2][0], self.elements[0][0], self.elements[0][2], self.elements[2][2]
# Set the middle squares
self.elements[0][1], self.elements[1][2], self.elements[2][1], self.elements[1][0] = self.elements[1][0], self.elements[0][1], self.elements[1][2], self.elements[2][1]
def rotate_counter_clockwise(self):
# Set the corners
self.elements[2][0], self.elements[0][0], self.elements[0][2], self.elements[2][2] = self.elements[0][0], self.elements[0][2], self.elements[2][2], self.elements[2][0]
# Set the middle squares
self.elements[1][0], self.elements[0][1], self.elements[1][2], self.elements[2][1] = self.elements[0][1], self.elements[1][2], self.elements[2][1], self.elements[1][0]
def refresh_game_canvas():
game_canvas.fill(black)
for row_idx, row in enumerate(grid):
for col_idx, element in enumerate(row):
if element is not None:
game_canvas.blit(element, (col_idx * 50 + 1, row_idx * 50 + 1))
# Display the current piece
for row_idx, row in enumerate(current_piece.elements):
for col_idx, element in enumerate(row):
if element is not None:
game_canvas.blit(element, ((col_idx + current_piece_position[1]) * 50 + 1, (row_idx + current_piece_position[0]) * 50 + 1))
def refresh_piece_preview_canvas():
piece_preview_canvas.fill(black)
non_empty_rows = list()
for row in next_piece.elements:
if any(map(lambda element: element is not None, row)):
non_empty_rows.append(row)
non_empty_cols = set()
for row in next_piece.elements:
for col_id, element in enumerate(row):
if element is not None:
non_empty_cols.add(col_id)
y_offset = (4 - len(non_empty_rows)) / 2
x_offset = (4 - len(non_empty_cols)) / 2
# Display the next piece
for row_idx, row in enumerate(non_empty_rows):
for col_idx, element in enumerate(row):
if element is not None:
piece_preview_canvas.blit(element, ((col_idx + x_offset) * 50 + 1, (row_idx + y_offset) * 50 + 1))
right_pane_canvas.blit(piece_preview_canvas, (50, 200))
def refresh_screen():
refresh_game_canvas()
screen.blit(game_canvas, (0, 0))
screen.blit(right_pane_canvas, (501, 0))
def has_collision(y: int, x: int) -> bool:
try:
for row_id, row in enumerate(current_piece.elements):
for col_id, element in enumerate(row):
if element is None:
continue
if row_id + y < 0:
continue
if col_id + x < 0:
return True
if grid[row_id + y][col_id + x] is not None:
return True
except IndexError:
return True
return False
def move_piece_down():
if not has_collision(current_piece_position[0] + 1, current_piece_position[1]):
current_piece_position[0] += 1
else:
raise WouldCollide()
def move_piece_up():
if not has_collision(current_piece_position[0] - 1, current_piece_position[1]):
current_piece_position[0] -= 1
else:
raise WouldCollide()
def move_piece_left():
if not has_collision(current_piece_position[0], current_piece_position[1] - 1):
current_piece_position[1] -= 1
else:
raise WouldCollide()
def move_piece_right():
if not has_collision(current_piece_position[0], current_piece_position[1] + 1):
current_piece_position[1] += 1
else:
raise WouldCollide()
def rotate_piece_counter_clockwise():
current_piece.rotate_counter_clockwise()
if has_collision(current_piece_position[0], current_piece_position[1]):
current_piece.rotate_clockwise()
raise WouldCollide()
def rotate_piece_clockwise():
current_piece.rotate_clockwise()
if has_collision(current_piece_position[0], current_piece_position[1]):
current_piece.rotate_counter_clockwise()
raise WouldCollide()
def generate_piece():
piece = random.choice((TPiece, SPiece, IPiece, ZPiece, SquarePiece))()
for row_id, row in enumerate(piece.elements):
if list(filter(lambda x: x is not None, row)):
break
initial_y_position = -row_id
initial_x_position = (len(grid[0]) // 2) - (len(piece.elements[0]) // 2)
return (piece, [initial_y_position, initial_x_position])
def burn_rows():
rows_to_burn = list()
for row in grid:
if all(map(lambda element: element is not None, row)):
rows_to_burn.append(row)
for row in rows_to_burn:
grid.insert(0, [None for _ in range(10)])
grid.remove(row)
def stick_piece():
global current_piece, current_piece_position, next_piece, next_piece_position
for row_id, row in enumerate(current_piece.elements):
for col_id, element in enumerate(row):
if element is None:
continue
grid[row_id + current_piece_position[0]][col_id + current_piece_position[1]] = element
burn_rows()
current_piece, current_piece_position = next_piece, next_piece_position
next_piece, next_piece_position = generate_piece()
refresh_piece_preview_canvas()
pygame.init()
black = (0, 0, 0)
white = (0xff, 0xff, 0xff)
blue = (0x10, 0x20, 0xbb)
green = (0x20, 0xbb, 0x10)
red = (0xbb, 0x10, 0x20)
yellow = (0xab, 0xd0, 0x20)
white_square = pygame.Surface((48, 48))
white_square.fill(white)
blue_square = pygame.Surface((48, 48))
blue_square.fill(blue)
green_square = pygame.Surface((48, 48))
green_square.fill(green)
red_square = pygame.Surface((48, 48))
red_square.fill(red)
yellow_square = pygame.Surface((48, 48))
yellow_square.fill(yellow)
screen = pygame.display.set_mode((801, 1000))
game_canvas = pygame.Surface((500, 1000))
right_pane_canvas = pygame.Surface((300, 1000))
right_pane_canvas.fill((255, 255, 255))
piece_preview_canvas = pygame.Surface((200, 200))
grid = [[None for _ in range(10)] for _ in range(20)]
current_piece, current_piece_position = generate_piece()
next_piece, next_piece_position = generate_piece()
refresh_piece_preview_canvas()
# Number of frames
frames_per_gridcell = 3
piece_drop_frames = 0
pygame.key.set_repeat(200, 50)
clock = pygame.time.Clock()
while True:
piece_drop_frames += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_ESCAPE, pygame.K_q):
sys.exit()
with contextlib.suppress(WouldCollide):
if event.key in (pygame.K_UP, pygame.K_k):
move_piece_up()
if event.key in (pygame.K_RIGHT, pygame.K_l):
move_piece_right()
if event.key in (pygame.K_LEFT, pygame.K_h):
move_piece_left()
if event.key == pygame.K_s:
rotate_piece_clockwise()
if event.key == pygame.K_d:
rotate_piece_counter_clockwise()
if event.key in (pygame.K_DOWN, pygame.K_j):
piece_drop_frames = 0
try:
move_piece_down()
except WouldCollide:
stick_piece()
if piece_drop_frames >= frames_per_gridcell:
piece_drop_frames = 0
try:
move_piece_down()
except WouldCollide:
stick_piece()
refresh_screen()
pygame.display.update()
clock.tick(60)
|