-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblocks.py
More file actions
559 lines (453 loc) · 15.6 KB
/
blocks.py
File metadata and controls
559 lines (453 loc) · 15.6 KB
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# Copyright 2025 wpdevelopment11
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE.txt file or at
# https://opensource.org/licenses/MIT.
from collections import namedtuple
from copy import copy
from enum import Enum, StrEnum
from functools import partial
from random import choice
from textwrap import dedent as d
from blessed import Terminal
import sys
import time
WIDTH = 10
HEIGHT = 22
TICK = 0.6
GAMEOVER = """\
GAME OVER
PRESS Q
TO QUIT.
PRESS R
TO
RESTART.
"""
Position = namedtuple("Position", ["x", "y"])
Square = namedtuple("Square", ["x", "y", "color"])
ColoredSymbol = namedtuple("ColoredSymbol", ["symbol", "color"])
class Screen(Enum):
"""Only used for learntris tests."""
TITLE = 0
GAME = 1
PAUSE = 2
GAMEOVER = 3
class Color(StrEnum):
EMPTY = "."
GREEN = "g"
RED = "r"
BLUE = "b"
MAGENTA = "m"
YELLOW = "y"
CYAN = "c"
ORANGE = "o"
NORMAL = "n"
class TetrominoShape(StrEnum):
I = d("""\
. . . .
c c c c
. . . .
. . . .
""")
O = d("""\
y y
y y
""")
Z = d("""\
r r .
. r r
. . .
""")
S = d("""\
. g g
g g .
. . .
""")
J = d("""\
b . .
b b b
. . .
""")
L = d("""\
. . o
o o o
. . .
""")
T = d("""\
. m .
m m m
. . .
""")
class Tetromino:
def __init__(self, shape, grid, pos=None):
self.shape = shape
self.matrix = [[Color(col) for col in row.split()] for row in self.shape.splitlines()]
self.grid = grid
self.pos = pos if pos is not None else Position(x=(grid.width - len(self.matrix[0])) // 2, y=0)
def rotate(self, counterclock=False):
matrix = self.rotate_matrix(self.matrix, counterclock)
if not self.is_valid_pos(self.pos, matrix):
return False
self.matrix = matrix
return True
@staticmethod
def rotate_matrix(matrix, counterclock=False):
matrix = [list(col) for col in zip(*matrix)]
if counterclock:
matrix = matrix[::-1]
else:
matrix = [row[::-1] for row in matrix]
return matrix
def is_valid_pos(self, pos, rotation=None):
matrix = self.matrix if rotation is None else rotation
grid = self.grid
rows = len(matrix)
cols = len(matrix[0])
for row in range(rows):
for col in range(cols):
if matrix[row][col] == Color.EMPTY:
continue
x = pos.x + col
y = pos.y + row
if not (x >= 0 and x < grid.width and y >= 0 and y < grid.height and grid.matrix[y][x] == Color.EMPTY):
return False
return True
def to_squares(self):
matrix = self.matrix
pos = self.pos
rows = len(matrix)
cols = len(matrix[0])
points = set()
for row in range(rows):
for col in range(cols):
color = matrix[row][col]
if color == Color.EMPTY:
continue
x = pos.x + col
y = pos.y + row
points.add(Square(x, y, color))
return points
def finalize(self):
pos = self.pos
matrix = self.matrix
grid = self.grid
rows = len(matrix)
cols = len(matrix[0])
for row in range(rows):
for col in range(cols):
if matrix[row][col] == Color.EMPTY:
continue
grid.matrix[pos.y + row][pos.x + col] = matrix[row][col]
def move_to_pos(self, pos):
if self.is_valid_pos(pos):
self.pos = pos
return True
return False
def move_left(self):
return self.move_to_pos(Position(self.pos.x-1, self.pos.y))
def move_right(self):
return self.move_to_pos(Position(self.pos.x+1, self.pos.y))
def move_up(self):
return self.move_to_pos(Position(self.pos.x, self.pos.y-1))
def move_down(self):
return self.move_to_pos(Position(self.pos.x, self.pos.y+1))
def can_move_left(self):
return self.is_valid_pos(Position(self.pos.x-1, self.pos.y))
def can_move_right(self):
return self.is_valid_pos(Position(self.pos.x+1, self.pos.y))
def can_move(self):
return self.can_move_left() or self.can_move_right()
def __str__(self):
return "\n".join([" ".join(row) for row in self.matrix])
class Game:
active_tetromino = None
next_shape = None
def __init__(self, grid, score=0, cleared=0, screen=Screen.GAME):
self.grid = grid
self.score = score
self.cleared = cleared
self.screen = screen
def clear_grid(self):
self.grid = Grid(self.grid.width, self.grid.height)
def clear_rows(self):
grid_width = self.grid.width
grid_height = self.grid.height
matrix = []
for row in self.grid.matrix:
if all([col != Color.EMPTY for col in row]):
self.cleared += 1
self.score += self.complete_row_score()
else:
matrix.append(row[:])
new_matrix = [[Color.EMPTY] * grid_width for _ in range(grid_height - len(matrix))]
new_matrix += matrix
self.grid.matrix = new_matrix
def complete_row_score(self):
return 100
def is_game_over(self):
matrix = self.grid.matrix
# Check the top two rows
return any([col != Color.EMPTY for row in matrix[0:2] for col in row])
def new_tetromino(self):
if self.next_shape is None:
shape = choice(list(TetrominoShape))
else:
shape = self.next_shape
self.active_tetromino = Tetromino(shape, self.grid)
self.next_shape = choice(list(TetrominoShape))
def __str__(self):
if self.active_tetromino is None or self.active_tetromino.pos is None:
return str(self.grid)
def get_color(row, col):
if (row >= pos.y and row < pos.y + rows
and col >= pos.x and col < pos.x + cols):
color = matrix[row-pos.y][col-pos.x]
if color != Color.EMPTY:
return color.upper()
return grid.matrix[row][col]
grid = self.grid
matrix = self.active_tetromino.matrix
pos = self.active_tetromino.pos
rows = len(matrix)
cols = len(matrix[0])
return "\n".join([" ".join([get_color(row, col) for col in range(grid.width)]) for row in range(grid.height)])
class Grid:
def __init__(self, width, height, cells=None):
self.width = width
self.height = height
self.matrix = [[Color.EMPTY] * width for _ in range(height)] if cells is None else cells
def __str__(self):
return "\n".join(
[" ".join(
[str(col) for col in row]) for row in self.matrix])
@classmethod
def from_str(cls, rows):
cells = [[Color(col) for col in row.split()] for row in rows]
width = len(cells[0])
height = len(cells)
assert width == WIDTH
assert height == HEIGHT
return cls(width, height, cells)
def filled_rows(self):
rows = []
for i, row in enumerate(self.matrix):
if all([col != Color.EMPTY for col in row]):
rows.append((i, row))
return rows
echo = partial(print, end='', flush=True)
class TerminalGame(Game):
def __init__(self, term, grid, origin, grid_border_size, score=0, cleared=0, screen=Screen.GAME):
super().__init__(grid, score, cleared, screen)
self.term = term
self.origin = origin
self.grid_border_size = grid_border_size
def draw(self):
tetromino = self.active_tetromino
shadow = copy(tetromino)
while shadow.move_down():
pass
a = tetromino.to_squares()
b = shadow.to_squares()
matrix = [row[:] for row in self.grid.matrix]
insert_into(matrix, a, "█")
insert_into(matrix, b - a, "░")
self.draw_rows(enumerate(matrix), "█")
def draw_status(self):
border = self.grid_border_size
x = self.origin.x + self.grid.width + (border * 2) + 2
y = self.origin.y + border
stats = d("""\
SCORE:
{}
LINES CLEARED:
{}
LEVEL:
{}
NEXT:
""").format(self.score, self.cleared, self.level).splitlines()
for line in stats:
echo(self.term.move_xy(x * 2, y) + line)
y += 1
# Clear previous
tallest = max([len(shape.splitlines()) for shape in TetrominoShape])
for dy in range(tallest):
echo(self.term.move_xy(x * 2, y + dy) + self.term.clear_eol)
next = Tetromino(self.next_shape, None, Position(x, y))
self.draw_squares(next.to_squares(), "█")
@property
def grid_pos(self):
border = self.grid_border_size
return Position(self.origin.x + border, self.origin.y + border)
def draw_squares(self, squares, symbol):
for square in squares:
colored = self.colored(square.color, symbol)
echo(self.term.move_xy(square.x * 2, square.y) + (colored * 2))
def draw_rows(self, rows, default_symbol):
grid_pos = self.grid_pos
for rownum, row in rows:
row = "".join([self.colored(element, default_symbol) * 2 for element in row])
echo(self.term.move_xy(grid_pos.x * 2, grid_pos.y + rownum) + row)
def colored(self, element, default_symbol=None):
if isinstance(element, ColoredSymbol):
symbol = element.symbol
color = element.color
elif isinstance(element, Color):
assert default_symbol is not None
symbol = default_symbol
color = element
else:
raise AssertionError("Never happens")
if color == Color.EMPTY:
return self.term.normal + " "
elif color == Color.NORMAL:
return self.term.normal + symbol
else:
return self.get_term_color(color)(symbol)
def draw_end_game(self):
term = self.term
grid = self.grid
text = GAMEOVER.splitlines()
text = text[:grid.height]
yoffset = (grid.height - len(text)) // 2
grid_pos = self.grid_pos
for line_num, line in enumerate(text):
line = line[:grid.width*2]
x = ((grid.width * 2) - len(line)) // 2
y = yoffset + line_num
echo(term.move_xy((grid_pos.x * 2) + x, grid_pos.y + y))
for char_num, ch in enumerate(line):
echo(self.background_color(x + char_num, y) + term.bold(ch))
echo(term.normal)
def background_color(self, x, y):
grid = self.grid
matrix = grid.matrix
x //= 2
return self.get_term_color(matrix[y][x], background=True)
def draw_borders(self, symbol):
origin = self.origin
grid = self.grid
border = self.grid_border_size
squares = []
for i in range(border):
for j in range(grid.width):
squares.append(Square(origin.x + border + j, origin.y + i, Color.NORMAL))
squares.append(Square(origin.x + border + j, origin.y + border + grid.height + i, Color.NORMAL))
for i in range(border):
for j in range(grid.height + (border * 2)):
squares.append(Square(origin.x + i, origin.y + j, Color.NORMAL))
squares.append(Square(origin.x + border + grid.width + i, origin.y + j, Color.NORMAL))
self.draw_squares(squares, symbol)
def read_key(self, timeout, last_move=False):
term = self.term
tetromino = self.active_tetromino
key = term.inkey(timeout)
code = key.code
is_moved = False
if key.lower() == "q":
sys.exit()
if code == term.KEY_LEFT:
is_moved = tetromino.move_left()
elif code == term.KEY_RIGHT:
is_moved = tetromino.move_right()
elif not last_move:
if code == term.KEY_UP:
is_moved = tetromino.rotate()
elif code == term.KEY_DOWN:
is_moved = tetromino.move_down()
elif key == ' ':
while tetromino.move_down():
is_moved = True
term.inkey(0.05)
self.draw()
return is_moved
def get_term_color(self, color, background=False):
color = color.name.lower()
if background:
color = "on_" + color
return getattr(self.term, color)
def complete_row_score(self):
return self.level * self.grid.width
@property
def level(self):
return (self.cleared // 10) + 1
@property
def tick_time(self):
return TICK / 1.2**(self.level - 1)
def increase_score(self):
"""Calculate the score for the dropped shape.
See here: https://perl.plover.com/qotw/e/023 how it's calculated.
"""
grid = self.grid
squares = self.active_tetromino.to_squares()
for s in squares:
adjacent = [
Position(s.x-1, s.y),
Position(s.x+1, s.y),
Position(s.x, s.y-1),
Position(s.x, s.y+1),
]
adjacent = [a for a in adjacent
if not (a.x >= 0 and a.x < grid.width and a.y >= 0 and a.y < grid.height)
or grid.matrix[a.y][a.x] != Color.EMPTY]
self.score += len(adjacent)
def debug(self, val):
term = self.term
echo(term.move_xy(0, term.height-1) + term.clear_eol + term.red(str(val)))
def insert_into(matrix, squares, symbol):
for s in squares:
assert matrix[s.y][s.x] == Color.EMPTY
matrix[s.y][s.x] = ColoredSymbol(symbol, s.color)
def start_game(term):
origin = Position(2, 1)
grid_border_size = 1
height = min(HEIGHT, term.height - origin.y - (grid_border_size * 2))
grid = Grid(WIDTH, height)
game = TerminalGame(term, grid, origin, grid_border_size)
game.new_tetromino()
echo(term.clear)
echo(term.move_xy(0, term.height-1))
game.draw_borders("█")
game.draw_status()
while True:
t1 = time.perf_counter()
game.draw()
while True:
if game.read_key(0.05):
game.draw()
t2 = time.perf_counter()
if t2 - t1 >= game.tick_time:
break
tetromino = game.active_tetromino
if not tetromino.move_down():
# Last chance to move left or right
if tetromino.can_move():
game.read_key(game.tick_time, last_move=True)
game.increase_score()
tetromino.finalize()
filled = game.grid.filled_rows()
if filled:
for i in range(1, 6):
if i % 2 == 1:
game.draw_rows(filled, "░")
else:
game.draw_rows(filled, "█")
term.inkey(0.2)
game.clear_rows()
if game.is_game_over():
game.draw_end_game()
break
else:
game.new_tetromino()
game.draw_status()
def main():
term = Terminal()
with term.fullscreen(), term.hidden_cursor(), term.cbreak():
start_game(term)
while True:
key = term.inkey().lower()
if key == "q":
break
elif key == "r":
start_game(term)
if __name__ == "__main__":
main()