-
Notifications
You must be signed in to change notification settings - Fork 0
/
tetromino.py
77 lines (61 loc) · 2.32 KB
/
tetromino.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
from settings import *
import random
class Block(pygame.sprite.Sprite):
def __init__(self, tetromino, pos):
self.tetromino = tetromino
self.pos = vec(pos) + INIT_POS_OFFSET
self.alive = True
super().__init__(tetromino.tetris.sprite_group)
self.image = tetromino.image
# self.image = pygame.Surface([TILE_SIZE, TILE_SIZE])
# pygame.draw.rect(
# self.image, "orange", (1, 1, TILE_SIZE - 2, TILE_SIZE - 2), border_radius=8
# )
self.rect = self.image.get_rect()
def is_alive(self):
if not self.alive:
self.kill()
def rotate(self, pivot_pos):
translated = self.pos - pivot_pos
rotated = translated.rotate(90)
return rotated + pivot_pos
def set_rect_pos(self):
self.rect.topleft = self.pos * TILE_SIZE
def update(self):
self.is_alive()
self.set_rect_pos()
def is_collide(self, pos):
x, y = int(pos.x), int(pos.y)
if (
0 <= x < FIELD_W
and y < FIELD_H
and (y < 0 or not self.tetromino.tetris.field_array[y][x])
):
return False
return True
class Tetromino:
def __init__(self, tetris):
self.tetris = tetris
self.shape = random.choice(list(TETROMINOES.keys()))
self.image = random.choice(tetris.app.images)
self.blocks = [Block(self, pos) for pos in TETROMINOES[self.shape]]
self.landing = False
def rotate(self):
pivot_pos = self.blocks[0].pos
new_block_positions = [block.rotate(pivot_pos) for block in self.blocks]
if not self.is_collide(new_block_positions):
for i, block in enumerate(self.blocks):
block.pos = new_block_positions[i]
def is_collide(self, block_positions):
return any(map(Block.is_collide, self.blocks, block_positions))
def move(self, direction):
move_direction = MOVE_DIRECTIONS[direction]
new_block_positions = [block.pos + move_direction for block in self.blocks]
is_collide = self.is_collide(new_block_positions)
if not is_collide:
for block in self.blocks:
block.pos += move_direction
elif direction == "down":
self.landing = True
def update(self):
self.move(direction="down")