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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
|
#!/usr/bin/env python3
import argparse
import contextlib
import enum
import random
import sys
import time
import pygame
from pycameltris.controller import KeyboardController, JoystickController, Input
class WouldCollide(Exception):
pass
class Piece():
def __init__(self):
self.square = square_template.copy()
def rotate_clockwise(self):
self.elements = list(zip(*self.elements[::-1]))
def rotate_counter_clockwise(self):
self.rotate_clockwise()
self.rotate_clockwise()
self.rotate_clockwise()
class ZPiece(Piece):
def __init__(self):
super().__init__()
self.square.fill(blue)
self.elements = (self.square, self.square, None), (None, self.square, self.square), (None, None, None)
self.vertical = False
def rotate_clockwise(self):
self.rotate()
def rotate_counter_clockwise(self):
self.rotate()
def rotate(self):
if self.vertical:
self.elements = (self.square, self.square, None), (None, self.square, self.square), (None, None, None)
else:
self.elements = (None, None, self.square), (None, self.square, self.square), (None, self.square, None)
self.vertical = not self.vertical
class SPiece(Piece):
def __init__(self):
super().__init__()
self.square.fill(green)
self.elements = (None, None, None), (None, self.square, self.square), (self.square, self.square, None)
self.vertical = False
def rotate_clockwise(self):
self.rotate()
def rotate_counter_clockwise(self):
self.rotate()
def rotate(self):
if self.vertical:
self.elements = (None, self.square, self.square), (self.square, self.square, None), (None, None, None)
else:
self.elements = (None, self.square, None), (None, self.square, self.square), (None, None, self.square)
self.vertical = not self.vertical
class SquarePiece(Piece):
def __init__(self):
super().__init__()
self.square.fill(brown)
self.elements = ((self.square, self.square), (self.square, self.square))
class IPiece(Piece):
def __init__(self):
super().__init__()
self.square.fill(red)
self.elements = (None, None, None, None), (None, None, None, None), (self.square, self.square, self.square, self.square), (None, None, None, None)
self.vertical = False
def rotate_clockwise(self):
self.rotate()
def rotate_counter_clockwise(self):
self.rotate()
def rotate(self):
if self.vertical:
self.elements = (None, None, None, None), (None, None, None, None), (self.square, self.square, self.square, self.square), (None, None, None, None)
else:
self.elements = (None, None, self.square, None), (None, None, self.square, None), (None, None, self.square, None), (None, None, self.square, None)
self.vertical = not self.vertical
class LPiece(Piece):
def __init__(self):
super().__init__()
self.square.fill(cyan)
self.elements = (None, None, None), (self.square, self.square, self.square), (None, None, self.square)
class JPiece(Piece):
def __init__(self):
super().__init__()
self.square.fill(purple)
self.elements = (None, None, None), (self.square, self.square, self.square), (self.square, None, None)
class TPiece(Piece):
def __init__(self):
super().__init__()
self.square.fill(yellow)
self.elements = (None, None, None), (self.square, self.square, self.square), (None, self.square, None)
def refresh_game_canvas():
global player
game_canvas.fill(black)
for row_idx, row in enumerate(player.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(player.current_piece.elements):
for col_idx, element in enumerate(row):
if element is not None:
game_canvas.blit(element, ((col_idx + player.current_piece_position[1]) * 50 + 1, (row_idx + player.current_piece_position[0]) * 50 + 1))
def refresh_right_pane_canvas():
level_canvas.fill(black)
score_canvas.fill(black)
if pygame.font:
score_font = pygame.font.Font(None, 56)
score_canvas.blit(score_font.render(f"{player.score:08d}", True, white), (0, 0))
level_canvas.blit(score_font.render(f"{player.level:08d}", True, white), (0, 0))
right_pane_canvas.blit(score_canvas, (2, 10))
right_pane_canvas.blit(level_canvas, (2, 70))
def refresh_piece_preview_canvas():
piece_preview_canvas.fill(black)
non_empty_rows = list()
for row in player.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 player.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))
refresh_right_pane_canvas()
screen.blit(right_pane_canvas, (501, 0))
class Player:
def __init__(self, controller):
self.controller = controller
self.grid = [[None for _ in range(10)] for _ in range(20)]
self.current_piece, self.current_piece_position = self.generate_piece()
self.next_piece, self.next_piece_position = self.generate_piece()
self.starting_level = self.level = 1
self.score = 0
self.lines_burnt = 0
self.das = 0
self.pressing_down_countdown = None
self.piece_drop_frames = 0
def generate_piece(self):
# We may want to make this a function outside the class
piece = random.choice((TPiece, SPiece, IPiece, ZPiece, SquarePiece, LPiece, JPiece))()
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(self.grid[0]) // 2) - (len(piece.elements[0]) // 2)
return (piece, [initial_y_position, initial_x_position])
def burn_rows(self):
rows_to_burn = list()
for row in self.grid:
if all(map(lambda element: element is not None, row)):
rows_to_burn.append(row)
for row in rows_to_burn:
self.grid.insert(0, [None for _ in range(10)])
self.grid.remove(row)
return len(rows_to_burn)
def stick_piece(self):
for row_id, row in enumerate(self.current_piece.elements):
for col_id, element in enumerate(row):
if element is None:
continue
self.grid[row_id + self.current_piece_position[0]][col_id + self.current_piece_position[1]] = element
count = self.burn_rows()
if count == 1:
print("Single")
rate = 1
elif count == 2:
print("Double")
rate = 2.5
elif count == 3:
print("Triple")
rate = 7.5
elif count == 4:
print("Tetris!")
rate = 30
else:
rate = 0
self.lines_burnt += count
self.score += int(self.level * 40 * rate)
if self.lines_burnt >= self.level * 10:
self.level += 1
self.current_piece, self.current_piece_position = self.next_piece, self.next_piece_position
self.next_piece, self.next_piece_position = self.generate_piece()
refresh_piece_preview_canvas()
def has_collision(self, y: int, x: int) -> bool:
try:
for row_id, row in enumerate(self.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 self.grid[row_id + y][col_id + x] is not None:
return True
except IndexError:
return True
return False
def move_piece_down(self):
if not self.has_collision(self.current_piece_position[0] + 1, self.current_piece_position[1]):
self.current_piece_position[0] += 1
else:
raise WouldCollide()
def move_piece_up(self):
if not self.has_collision(self.current_piece_position[0] - 1, self.current_piece_position[1]):
self.current_piece_position[0] -= 1
else:
raise WouldCollide()
def move_piece_left(self):
if not self.has_collision(self.current_piece_position[0], self.current_piece_position[1] - 1):
self.current_piece_position[1] -= 1
else:
raise WouldCollide()
def move_piece_right(self):
if not self.has_collision(self.current_piece_position[0], self.current_piece_position[1] + 1):
self.current_piece_position[1] += 1
else:
raise WouldCollide()
def rotate_piece_counter_clockwise(self):
self.current_piece.rotate_counter_clockwise()
if self.has_collision(self.current_piece_position[0], self.current_piece_position[1]):
self.current_piece.rotate_clockwise()
raise WouldCollide()
def rotate_piece_clockwise(self):
self.current_piece.rotate_clockwise()
if has_collision(self.current_piece_position[0], self.current_piece_position[1]):
self.current_piece.rotate_counter_clockwise()
raise WouldCollide()
PARSER = argparse.ArgumentParser()
PARSER.add_argument("--starting-level", type=int, choices=list(range(1, 30)), default=1)
PARSER.add_argument("--joystick", type=int, dest="joystick_id", metavar="Joystick ID")
ARGS = vars(PARSER.parse_args())
print(ARGS)
pygame.init()
black = (0, 0, 0)
white = (0xff, 0xff, 0xff)
brown = (163, 75, 31)
blue = (30, 34, 164)
green = (30, 164, 59)
red = (164, 30, 30)
purple = (126, 30, 164)
yellow = (164, 164, 30)
cyan = (30, 164, 150)
square_template = pygame.Surface((48, 48))
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))
score_canvas = pygame.Surface((296, 50))
level_canvas = pygame.Surface((296, 50))
if ARGS["joystick_id"] is not None:
joystick = pygame.joystick.Joystick(ARGS["joystick_id"])
joystick.init()
controller = JoystickController(joystick)
else:
controller = KeyboardController(pygame.key)
player = Player(controller)
refresh_piece_preview_canvas()
# Number of frames
frames_per_gridcell = [48, 43, 38, 33, 28, 23, 18, 13, 8, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
clock = pygame.time.Clock()
while True:
player.piece_drop_frames += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == controller.downevent:
if controller.get_input_down(event) == Input.QUIT:
sys.exit()
with contextlib.suppress(WouldCollide):
if controller.get_input_down(event) == Input.MOVE_RIGHT:
player.move_piece_right()
player.das = 0
if controller.get_input_down(event) == Input.MOVE_LEFT:
player.move_piece_left()
player.das = 0
if controller.get_input_down(event) == Input.ROTATE_CLOCKWISE:
player.rotate_piece_clockwise()
if controller.get_input_down(event) == Input.ROTATE_COUNTER_CLOCKWISE:
player.rotate_piece_counter_clockwise()
if controller.get_input_down(event) == Input.MOVE_DOWN:
player.piece_drop_frames = 0
player.pressing_down_countdown = 3
try:
player.move_piece_down()
except WouldCollide:
player.stick_piece()
elif event.type == controller.upevent:
if controller.get_input_up(event) == Input.MOVE_DOWN:
player.pressing_down_countdown = None
player.das += 1
if player.das == 16:
with contextlib.suppress(WouldCollide):
if controller.is_pressed(Input.MOVE_RIGHT):
player.move_piece_right()
if controller.is_pressed(Input.MOVE_LEFT):
player.move_piece_left()
player.das = 10
if player.pressing_down_countdown == 0:
try:
player.move_piece_down()
except WouldCollide:
player.stick_piece()
player.pressing_down_countdown = 2
elif player.pressing_down_countdown is not None:
player.pressing_down_countdown -= 1
if player.piece_drop_frames >= frames_per_gridcell[player.level - 1]:
player.piece_drop_frames = 0
try:
player.move_piece_down()
except WouldCollide:
player.stick_piece()
refresh_screen()
pygame.display.update()
clock.tick(60)
|