-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtetris.py
844 lines (734 loc) · 30.8 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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
import random
import time
from enum import Enum
from typing import Protocol
import pygame
from pygame import mixer, Surface
from db import DB
from time_tracking import TimeTracking
from settings import (
SCREEN, BLACK, WHITE, SKY_BLUE, BLUE, ORANGE, YELLOW, GREEN, PURPLE, RED, DESCENT_SPEED, X_LENGTH, Y_LENGTH
)
class Move(Enum):
"""Movement options in the game."""
UP = 0
LEFT = 1
RIGHT = 2
DOWN = 3
class Block(Protocol):
def turn(self) -> None:
"""Perform a turn action of the block in the game.
The function checks if the current block can rotate without colliding with any other blocks.
If it can, the function updates the positions of the current blocks accordingly.
The position of the block depends also on the state of the block.
"""
...
@staticmethod
def draw() -> None:
"""Draw the block in the waiting area."""
...
class BackgroundBlock:
def __init__(self, x: int, y: int, number: int, not_block: bool):
"""
Every block has a number.
0 is not block, 1 to 7 is block, 8 is boundary.
not_block shows whether this block is a boundary or an installed block.
"""
self.x = x
self.y = y
self.number = number
self.not_block = not_block
@property
def color(self) -> tuple:
"""Return the color related with each block type."""
if self.number == 1:
return SKY_BLUE
elif self.number == 2:
return BLUE
elif self.number == 3:
return ORANGE
elif self.number == 4:
return YELLOW
elif self.number == 5:
return GREEN
elif self.number == 6:
return PURPLE
elif self.number == 7:
return RED
@staticmethod
def color_the_block(screen: Surface, coordinates: tuple, x: int, y: int) -> None:
pygame.draw.rect(screen, coordinates, pygame.Rect(32 * x, 32 * y, 32, 32))
pygame.draw.rect(screen, BLACK, pygame.Rect(32 * x, 32 * y, 32, 32), width=1)
background_blocks = [[0 for j in range(X_LENGTH)] for i in range(Y_LENGTH)] # Game Screen consisting of 12 × 21 blocks
class Tetris:
mixer.init()
break_sound = mixer.Sound("resources/audio/202230__deraj__pop-sound.wav")
break_sound.set_volume(0.2)
erase_sound = mixer.Sound("resources/audio/143607__dwoboyle__menu-interface-confirm-003.wav")
erase_sound.set_volume(0.15)
def __init__(self):
self.score = 0
self.gameover = False
self.number_of_blocks = 0 # How many blocks were made?
self.block_number = 0
self.next_blocks = [] # The background blocks where moving blocks will be placed.
self.current_blocks = [] # The background blocks where moving blocks are placed.
self.current_y_list = [] # y-coordinate list of moving blocks
self.current_x_list = [] # x-coordinate list of moving blocks
self._state = 0 # You can turn the block four times. 0, 1, 2, 3
@property
def state(self):
return self._state
@state.setter
def state(self, value):
"""Checks the bounds of the state value and wraps the value when necessary before setting"""
if value in range(4):
self._state = value
elif value > 3:
self._state = 0
elif value < 0:
self._state = 3
def gameover_state(self):
# What if there are other blocks where they will be?
return any(i in self.next_blocks for i in range(1, 8))
def start(self, ti: TimeTracking, current_block: Block):
self.block_number = current_block.number
self.number_of_blocks += 1
ti.start_time = time.time()
def current_iter(block_number, blocks):
for block in iter(blocks): # What if there are no other blocks where they will be?
block.number = block_number # Create the blocks on the game screen
yield block
self.next_blocks.clear()
# A lazily-evaluated map of background blocks. Used to fetch and place one in next_blocks.
fetch_blocks_map = [
lambda group: group[0][4:8], # Block I (1)
lambda group: [group[0][4], *group[1][4:7]], # Block J (2)
lambda group: [*group[1][4:7], group[0][6]], # Block L (3)
lambda group: [block for blocks in group[0:2] for block in blocks[5:7]], # Block O (4)
lambda group: [*group[1][4:6], *group[0][5:7]], # Block S (5)
lambda group: [group[0][5], *group[1][4:7]], # Block T (6)
lambda group: [*group[0][4:6], *group[1][5:7]], # Block Z (7)
]
fetcher = fetch_blocks_map[self.block_number - 1]
blocks = fetcher(background_blocks)
self.next_blocks.extend(block.number for block in blocks)
self.gameover = self.gameover_state()
if self.gameover:
return
self.current_blocks.extend(current_iter(self.block_number, blocks))
self._state = 0
def go(self, move: Enum, ti: TimeTracking):
self.next_blocks.clear()
if move in (Move.LEFT, Move.RIGHT):
if move == Move.LEFT:
adjust = -1
else:
adjust = 1
for i in range(4):
self.next_blocks.append(
background_blocks[self.current_blocks[i].y//32][(self.current_blocks[i].x//32)+adjust]
)
if self.next_blocks[i].number in range(1, 9) and self.next_blocks[i].not_block:
return
elif move == Move.DOWN:
for i in range(4):
self.next_blocks.append(
background_blocks[(self.current_blocks[i].y//32) + 1][(self.current_blocks[i].x//32)]
)
# Add background blocks in where the blocks are moving
if self.next_blocks[i].number in range(1, 9) and self.next_blocks[i].not_block:
# If there are blocks down there, stop
y_list = []
for j in range(4):
self.current_blocks[j].not_block = True
y_list.append(self.current_blocks[j].y)
self.current_blocks.clear()
self.break_sound.play()
ti.update_time(time.time(), self.number_of_blocks)
self.erase_line_plus_score(y_list, self.erase_sound)
return y_list
self.clear() # The block is now moving! Remove the background blocks color beforehand.
for i in range(4):
self.current_blocks[i] = self.next_blocks[i]
self.current_blocks[i].number = self.block_number
def clear(self):
for i in range(4):
self.current_blocks[i].number = 0
pygame.draw.rect(SCREEN, BLACK, pygame.Rect(self.current_blocks[i].x, self.current_blocks[i].y, 32, 32))
def erase_line_plus_score(self, y_list: list, erase_sound: mixer.Sound):
"""
max_y is largest y-index of placed blocks.
min_y is smallest y-index of placed blocks minus 1.
Check that all horizontal lines are full.
"""
max_y = max(y_list)//32
min_y = min(y_list)//32 - 1
while max_y > min_y:
count = 0
for x in range(1, 11):
if not background_blocks[max_y][x].not_block: # If any of the 10 blocks is empty
break
count += 1
if count == 10:
erase_sound.play()
for x in range(1, 11):
background_blocks[max_y][x].not_block = False
background_blocks[max_y][x].number = 0
pygame.draw.rect(
SCREEN, BLACK, pygame.Rect(background_blocks[max_y][x].x, background_blocks[max_y][x].y, 32, 32) # noqa
)
for y2 in range(max_y, 0, -1):
for x in range(1, 11):
background_blocks[y2][x].not_block = background_blocks[y2-1][x].not_block
background_blocks[y2][x].number = background_blocks[y2-1][x].number
background_blocks[y2-1][x].not_block = False
background_blocks[y2-1][x].number = 0
pygame.draw.rect(
SCREEN, BLACK, pygame.Rect(background_blocks[y2-1][x].x, background_blocks[y2-1][x].y, 32, 32) # noqa
)
self.score += 100
max_y += 1
min_y += 1
max_y -= 1
def rotate(self, block: Block):
if not block.turnable:
return
self.clear()
block.render_background_blocks()
self.state += 1
def refresh(self):
self.current_y_list.clear()
self.current_x_list.clear()
for i in range(4):
self.current_y_list.append(self.current_blocks[i].y//32)
self.current_x_list.append(self.current_blocks[i].x//32)
class BlockI():
def __init__(self, tetris: Tetris):
self.number = 1
self.tetris = tetris
self._turnable_check_indexes = [
(0, 0),
(0, 3),
(0, 0),
(0, 0),
]
self._render_block_indexes = [
(2, 2),
(1, 1),
(2, 2),
(1, 1),
]
self._turnable_offset_iters = [
[(y, x) for x in range(4) for y in [-1, 1, 2]],
[
*((y, -1) for y in range(4)),
*((y, 1) for y in range(4)),
*((y, -2) for y in range(4)),
],
[(y, -x) for x in range(4) for y in [1, -1, -2]],
[
*((y, -1) for y in range(4)),
*((y, 1) for y in range(4)),
*((y, 2) for y in range(4)),
],
]
self._render_offset_iters = [
[(2 - y, 0) for y in range(4)],
[(0, 1 - x) for x in range(4)],
[(y - 2, 0) for y in range(4)],
[(0, x - 1) for x in range(4)],
]
@property
def turnable(self):
state = self.tetris.state
if state == 0 and self.tetris.current_y_list[0] == 0:
return False
y, x = self._turnable_check_indexes[state]
current_y = self.tetris.current_y_list[y]
current_x = self.tetris.current_x_list[x]
for oy, ox in self._turnable_offset_iters[state]:
if background_blocks[current_y + oy][current_x + ox].not_block:
return False
return True
def render_background_blocks(self):
state = self.tetris.state
y, x = self._render_block_indexes[state]
current_y = self.tetris.current_y_list[y]
current_x = self.tetris.current_x_list[x]
blocks_to_render = (
background_blocks[current_y + oy][current_x + ox]
for oy, ox in self._render_offset_iters[state]
)
for i, block in enumerate(blocks_to_render):
block.number = self.tetris.block_number
self.tetris.current_blocks[i] = block
def turn(self):
self.tetris.refresh()
self.tetris.rotate(self)
@staticmethod
def draw():
for x in range(14, 18):
pygame.draw.rect(SCREEN, SKY_BLUE, pygame.Rect(32 * x + 16, 32 * 12, 32, 32))
class BlockJ():
def __init__(self, tetris: Tetris):
self.number = 2
self.tetris = tetris
self._turnable_check_indexes = [
[(1, 1), (0, 0)],
[(1, 1), (0, 0)],
[(1, 1), (0, 0)],
[(3, 1), (0, 0)],
]
self._render_block_indexes = [
[(0, 0), (2, 2)],
[(0, 0), (0, 0)],
[(0, 0), (2, 2)],
[(0, 0), (0, 0)],
]
self._turnable_offsets = [
[lambda x: (1, x), lambda x: (0, x + 1)],
[lambda y: (y, -1), lambda y: (y + 1, 0)],
[lambda x: (-1, -x), lambda x: (0, x - 1)],
[lambda y: (y, 1), lambda y: (y - 2, 0)],
]
self._render_offsets = [
[(0, 2), lambda y: (y - 1, 0)],
[(2, 0), lambda x: (1, -x)],
[(0, -2), lambda y: (1 - y, 0)],
[(-2, 0), lambda x: (-1, x)],
]
@property
def turnable(self):
state = self.tetris.state
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._turnable_check_indexes[state]
]
blocks_to_check = zip(coords, self._turnable_offsets[state], [3, 2])
for (y, x), offset_func, offsets in blocks_to_check:
for i in range(offsets):
oy, ox = offset_func(i)
if background_blocks[y + oy][x + ox].not_block:
return False
return True
def render_background_blocks(self):
state = self.tetris.state
(y1, x1), (y2, x2) = self._render_block_indexes[state]
current_y = self.tetris.current_y_list[y1]
current_x = self.tetris.current_x_list[x1]
offset, offset_func = self._render_offsets[state]
block = background_blocks[current_y + offset[0]][current_x + offset[1]]
block.number = self.tetris.block_number
self.tetris.current_blocks[0] = block
current_y = self.tetris.current_y_list[y2]
current_x = self.tetris.current_x_list[x2]
for i in range(3):
y, x = offset_func(i)
block = background_blocks[current_y + y][current_x + x]
block.number = self.tetris.block_number
self.tetris.current_blocks[i + 1] = block
def turn(self):
self.tetris.refresh()
self.tetris.rotate(self)
@staticmethod
def draw():
for x in range(15, 18):
pygame.draw.rect(SCREEN, BLUE, pygame.Rect(32 * x, 32 * 12, 32, 32))
pygame.draw.rect(SCREEN, BLUE, pygame.Rect(32 * 15, 32 * 11, 32, 32))
class BlockL():
def __init__(self, tetris: Tetris):
self.number = 3
self.tetris = tetris
self._turnable_check_indexes = [
[(0, 0), (3, 3)],
[(0, 0), (0, 0)],
[(2, 2), (3, 3)],
[(2, 0), (3, 3)],
]
self._render_block_indexes = [
[(1, 1), (2, 2)],
[(1, 1), (2, 2)],
[(1, 1), (2, 2)],
[(1, 1), (2, 2)],
]
self._turnable_offsets = [
[lambda x: (1, x), lambda x: (3, x - 2)],
[lambda y: (y, -1), lambda y: (y, 1)],
[lambda x: (-1, x), lambda x: (0, x + 1)],
[lambda y: (y, 1), lambda y: (y + 1, 0)],
]
self._render_offsets = [
[lambda y: (y - 1, 0), (1, 0)],
[lambda x: (0, 1 - x), (0, -1)],
[lambda y: (1 - y, 0), (-1, 0)],
[lambda x: (0, x - 1), (0, 1)],
]
@property
def turnable(self):
state = self.tetris.state
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._turnable_check_indexes[state]
]
blocks_to_check = zip(coords, self._turnable_offsets[state], [3, 2])
for (y, x), offset_func, offsets in blocks_to_check:
for i in range(offsets):
oy, ox = offset_func(i)
if background_blocks[y + oy][x + ox].not_block:
return False
return True
def render_background_blocks(self):
state = self.tetris.state
offset_func, offset = self._render_offsets[state]
(y1, x1), (y2, x2) = self._render_block_indexes[state]
current_y = self.tetris.current_y_list[y1]
current_x = self.tetris.current_x_list[x1]
for i in range(3):
oy, ox = offset_func(i)
block = background_blocks[current_y + oy][current_x + ox]
block.number = self.tetris.block_number
self.tetris.current_blocks[i] = block
current_y = self.tetris.current_y_list[y2]
current_x = self.tetris.current_x_list[x2]
block = background_blocks[current_y + offset[0]][current_x + offset[1]]
block.number = self.tetris.block_number
self.tetris.current_blocks[3] = block
def turn(self):
self.tetris.refresh()
self.tetris.rotate(self)
@staticmethod
def draw():
for x in range(15, 18):
pygame.draw.rect(SCREEN, ORANGE, pygame.Rect(32 * x, 32 * 12, 32, 32))
pygame.draw.rect(SCREEN, ORANGE, pygame.Rect(32 * 17, 32 * 11, 32, 32))
class BlockO():
def __init__(self, tetris: Tetris):
self.number = 4
self.tetris = tetris
def turn(self):
pass
@staticmethod
def draw():
for x in range(15, 17):
for y in range(11, 13):
pygame.draw.rect(SCREEN, YELLOW, pygame.Rect(32 * x + 16, 32 * y, 32, 32))
class BlockS():
def __init__(self, tetris: Tetris):
self.number = 5
self.tetris = tetris
self._turnable_check_indexes = [
[(2, 0), (0, 0), (1, 1)],
[(0, 2), (1, 1), (2, 2)],
[(2, 3), (0, 0), (2, 0)],
[(0, 2), (1, 1), (2, 2)],
]
self._render_block_indexes = [
[(0, 0), (1, 1)],
[(0, 0), (1, 1)],
[(0, 0), (1, 1)],
[(0, 0), (1, 1)],
]
self._turnable_offsets = [
[lambda x: (-1, x), (-1, 0), (0, 1)],
[lambda y: (y, 1), (1, 0), (-1, 0)],
[lambda x: (1, x), (0, -2), (0, 0)],
[lambda y: (-y, -1), (-1, 0), (1, 0)],
]
self._render_offsets = [
[lambda y: (y - 2, 0), lambda y: (y - 1, 0)],
[lambda x: (0, 2 - x), lambda x: (0, 1 - x)],
[lambda y: (2 - y, 0), lambda y: (1 - y, 0)],
[lambda x: (0, x - 2), lambda x: (0, x - 1)],
]
@property
def turnable(self):
state = self.tetris.state
if state == 0 and self.tetris.current_y_list[2] == 0:
return False
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._turnable_check_indexes[state]
]
y, x = coords[0]
offset_func = self._turnable_offsets[state][0]
for i in range(3):
oy, ox = offset_func(i)
if background_blocks[y + oy][x + ox].not_block:
return False
blocks_to_check = zip(coords[1:], self._turnable_offsets[state][1:])
for (y, x), (oy, ox) in blocks_to_check:
if background_blocks[y + oy][x + ox].not_block:
return False
return True
def render_background_blocks(self):
state = self.tetris.state
(y1, x1), (y2, x2) = self._render_block_indexes[state]
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._render_block_indexes[state]
]
blocks_to_render = zip(coords, self._render_offsets[state], [0, 2])
for (y, x), offset_func, block_offset in blocks_to_render:
for i in range(2):
oy, ox = offset_func(i)
block = background_blocks[y + oy][x + ox]
block.number = self.tetris.block_number
self.tetris.current_blocks[i + block_offset] = block
def turn(self):
self.tetris.refresh()
self.tetris.rotate(self)
@staticmethod
def draw():
for x in range(16, 18):
pygame.draw.rect(SCREEN, GREEN, pygame.Rect(32 * x, 32 * 11, 32, 32))
for x in range(15, 17):
pygame.draw.rect(SCREEN, GREEN, pygame.Rect(32 * x, 32 * 12, 32, 32))
class BlockT():
def __init__(self, tetris: Tetris):
self.number = 6
self.tetris = tetris
self._turnable_check_indexes = [
[(1, 1), (0, 1), (0, 3)],
[(1, 1), (0, 0), (0, 0)],
[(1, 3), (0, 0), (0, 0)],
[(3, 1), (0, 0), (0, 0)],
]
self._render_block_indexes = [
[(3, 3), (0, 0)],
[(3, 3), (0, 0)],
[(3, 3), (2, 0)],
[(3, 3), (0, 0)],
]
self._turnable_offsets = [
[lambda x: (1, x), (0, 0), (0, 0)],
[lambda y: (y, -1), (-1, 0), (1, 0)],
[lambda x: (-1, x), (0, -1), (0, 1)],
[lambda y: (y, 1), (-1, 0), (1, 0)],
]
self._render_offsets = [
[(0, 0), lambda y: (y, 0)],
[(0, 0), lambda x: (0, -x)],
[(0, 0), lambda y: (1 - y, 0)],
[(0, 0), lambda x: (0, x)],
]
@property
def turnable(self):
state = self.tetris.state
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._turnable_check_indexes[state]
]
y, x = coords[0]
offset_func = self._turnable_offsets[state][0]
for i in range(3):
oy, ox = offset_func(i)
if background_blocks[y + oy][x + ox].not_block:
return False
blocks_to_check = zip(coords[1:], self._turnable_offsets[state][1:])
for (y, x), (oy, ox) in blocks_to_check:
if background_blocks[y + oy][x + ox].not_block:
return False
return True
def render_background_blocks(self):
state = self.tetris.state
(y1, x1), (y2, x2) = self._render_block_indexes[state]
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._render_block_indexes[state]
]
y, x = coords[0]
oy, ox = self._render_offsets[state][0]
block = background_blocks[y + oy][x + ox]
block.number = self.tetris.block_number
self.tetris.current_blocks[0] = block
y, x = coords[1]
offset_func = self._render_offsets[state][1]
for i in range(3):
oy, ox = offset_func(i)
block = background_blocks[y + oy][x + ox]
block.number = self.tetris.block_number
self.tetris.current_blocks[i + 1] = block
def turn(self):
self.tetris.current_y_list.clear()
self.tetris.current_x_list.clear()
for i in range(4):
self.tetris.current_y_list.append(self.tetris.current_blocks[i].y//32)
self.tetris.current_x_list.append(self.tetris.current_blocks[i].x//32)
self.tetris.rotate(self)
@staticmethod
def draw():
for x in range(15, 18):
pygame.draw.rect(SCREEN, PURPLE, pygame.Rect(32 * x, 32 * 12, 32, 32))
pygame.draw.rect(SCREEN, PURPLE, pygame.Rect(32 * 16, 32 * 11, 32, 32))
class BlockZ():
def __init__(self, tetris: Tetris):
self.number = 7
self.tetris = tetris
self._turnable_check_indexes = [
[(0, 0), (0, 3), (2, 0)],
[(0, 0), (0, 2), (3, 0)],
[(0, 3), (0, 3), (2, 0)],
[(3, 0), (0, 2), (3, 0)],
]
self._render_block_indexes = [
[(1, 1), (0, 0)],
[(1, 1), (0, 0)],
[(1, 1), (0, 0)],
[(1, 1), (0, 0)],
]
self._turnable_offsets = [
[lambda x: (-1, x), (0, 0), (0, 0)],
[lambda y: (y, 1), (0, 0), (0, 0)],
[lambda x: (1, x), (0, 0), (0, 0)],
[lambda y: (y, -1), (0, 0), (0, 0)],
]
self._render_offsets = [
[lambda y: (y - 1, 0), lambda y: (y, 0)],
[lambda x: (0, 1 - x), lambda x: (0, -x)],
[lambda y: (1 - y, 0), lambda y: (-y, 0)],
[lambda x: (0, x - 1), lambda x: (0, x)],
]
@property
def turnable(self):
state = self.tetris.state
if state == 0 and self.tetris.current_y_list[0] == 0:
return False
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._turnable_check_indexes[state]
]
y, x = coords[0]
offset_func = self._turnable_offsets[state][0]
for i in range(3):
oy, ox = offset_func(i)
if background_blocks[y + oy][x + ox].not_block:
return False
blocks_to_check = zip(coords[1:], self._turnable_offsets[state][1:])
for (y, x), (oy, ox) in blocks_to_check:
if background_blocks[y + oy][x + ox].not_block:
return False
return True
def render_background_blocks(self):
state = self.tetris.state
(y1, x1), (y2, x2) = self._render_block_indexes[state]
coords = [
(self.tetris.current_y_list[y], self.tetris.current_x_list[x])
for y, x in self._render_block_indexes[state]
]
blocks_to_render = zip(coords, self._render_offsets[state], [0, 2])
for (y, x), offset_func, block_offset in blocks_to_render:
for i in range(2):
oy, ox = offset_func(i)
block = background_blocks[y + oy][x + ox]
block.number = self.tetris.block_number
self.tetris.current_blocks[i + block_offset] = block
def turn(self):
self.tetris.refresh()
self.tetris.rotate(self)
@staticmethod
def draw():
for x in range(15, 17):
pygame.draw.rect(SCREEN, RED, pygame.Rect(32 * x, 32 * 11, 32, 32))
for x in range(16, 18):
pygame.draw.rect(SCREEN, RED, pygame.Rect(32 * x, 32 * 12, 32, 32))
def main():
block_shape_list = [BlockI, BlockJ, BlockL, BlockO, BlockS, BlockT, BlockZ]
def check_and_go_down(ti: TimeTracking, current_block: Block, next_block: Block):
"""Check if the block can go down and do it if it is possible.
Args:
ti (Time): Current time
current_block (Tetris): Current block
next_block (Tetris): Next block
Returns:
current_block, next_block: the updated blocks if the movement was possible, the same blocks otherwise.
"""
if type(tetris.go(Move.DOWN, ti)) == list:
current_block = next_block
next_block = random.choice(block_shape_list)(tetris)
tetris.start(ti, current_block)
return current_block, next_block
pygame.init() # The coordinate (0, 0) is in the upper left.
tetris = Tetris()
db = DB()
score_list = db.fetch_highest_score()
ti = TimeTracking()
font_score = pygame.font.SysFont("consolas", 30)
font_game_over = pygame.font.SysFont("ebrima", 100)
font_best = pygame.font.SysFont("consolas", 20)
font_average_time = pygame.font.SysFont("consolas", 15)
pygame.display.set_caption("Tetris") # Title
pygame.key.set_repeat(120) # Control how held keys are repeated
clock = pygame.time.Clock() # Create an object to help track time
mixer.init()
mixer.music.load("resources/audio/580898__bloodpixelhero__in-game.wav")
mixer.music.set_volume(0.04)
mixer.music.play()
for y in range(Y_LENGTH): # Create blocks that make up the game screen
for x in range(X_LENGTH):
if x in [0, 11] or y == 20: # The blocks that make up the boundary
background_blocks[y][x] = BackgroundBlock(32 * x, 32 * y, 8, True)
else:
background_blocks[y][x] = BackgroundBlock(32 * x, 32 * y, 0, False)
descent_var = 0
current_block = random.choice(block_shape_list)(tetris) # Randomly select one of the seven types of blocks
next_block = random.choice(block_shape_list)(tetris)
tetris.start(ti, current_block) # First block appears on the game screen
running = True
while running:
SCREEN.fill(BLACK) # Paint the SCREEN black before draw blocks on SCREEN
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
current_block.turn()
elif event.key == pygame.K_DOWN:
descent_var = 0
current_block, next_block = check_and_go_down(ti, current_block, next_block)
elif event.key == pygame.K_LEFT:
tetris.go(Move.LEFT, ti)
elif event.key == pygame.K_RIGHT:
tetris.go(Move.RIGHT, ti)
descent_var += 1
if descent_var % DESCENT_SPEED == 0:
current_block, next_block = check_and_go_down(ti, current_block, next_block)
# The block automatically goes down If you don't press down key.
score_info = font_score.render("Score : " + str(tetris.score), True, WHITE)
SCREEN.blit(score_info, (387, 15))
avg_time_info = font_average_time.render(f"Average time to put a block : {ti.avg_time:.2f}s", True, WHITE)
SCREEN.blit(avg_time_info, (387, 55))
best_time_info = font_best.render(f"Best : {score_list[0][0]} / {score_list[0][1]:.2f}", True, WHITE)
SCREEN.blit(best_time_info, (387, 635))
pygame.draw.rect(SCREEN, (211, 211, 211), pygame.Rect(32 * 14, 32 * 10, 32*5, 32*4), width=3) # Border
next_block.draw() # Draw the next block to come out in the waiting area
for x in range(1, 11): # Color the boundaries of the blocks on the game screen
for y in range(20):
pygame.draw.rect(SCREEN, (161, 145, 61), pygame.Rect(32 * x, 32 * y, 32, 32), width=1)
for y in range(Y_LENGTH): # Color the blocks on the game screen
for x in range(X_LENGTH):
if background_blocks[y][x].number in range(1, 8):
BackgroundBlock.color_the_block(SCREEN, background_blocks[y][x].color, x, y)
elif background_blocks[y][x].number == 8:
pygame.draw.rect(SCREEN, (128, 128, 128), pygame.Rect(32 * x, 32 * y, 32, 32))
if tetris.gameover:
pygame.draw.rect(SCREEN, BLACK, pygame.Rect(32 * 1, 32 * 3, 32 * 19, 32 * 15))
pygame.draw.rect(SCREEN, WHITE, pygame.Rect(32 * 1, 32 * 3, 32 * 19, 32 * 15), width=3)
gameover_text = font_game_over.render("GAME OVER!", True, WHITE)
SCREEN.blit(gameover_text, (50, 220))
score_info = font_score.render("Score : " + str(tetris.score), True, WHITE)
SCREEN.blit(score_info, (70, 360))
avg_time_info = font_average_time.render(f"Average time to put a block : {ti.avg_time:.2f}s", True, WHITE)
SCREEN.blit(avg_time_info, (70, 400))
gameover_sound = mixer.Sound("resources/audio/42349__irrlicht__game-over.wav")
gameover_sound.set_volume(0.2)
gameover_sound.play()
pygame.display.flip()
db.save_highest_score(tetris.score, ti.avg_time)
pygame.time.wait(2000)
running = False
pygame.display.flip() # It makes the screen to be updated continuously
clock.tick(30) # In main loop, it determine FPS
pygame.quit()
if __name__ == "__main__":
main()