Files
PyGame-Tetris/bricks.py
2025-04-23 13:45:29 +02:00

88 lines
3.0 KiB
Python

import pygame
from globals import BRICKS, TILE_SIZE, GRID_WIDTH, GRID_HEIGHT, grid
import enums
from random import choice
class Brick:
def __init__(self, brick, state = enums.BrickState.Next):
self.layout = []
self.color = choice(list(enums.BrickColor))
self.set_state(state)
self.angle = 0
self.direction = None
self.load_brick(brick)
self.get_image()
self.block_image = pygame.transform.scale(self.img, (48, 48)) if self.img else None
self.draw_brick()
self.x, self.y = (3, 0)
self.location = list((self.x, self.y))
def get_image(self):
match self.color:
case enums.BrickColor.Magenta:
self.img = pygame.image.load("assets/magenta_block.png").convert_alpha()
case enums.BrickColor.Cyan:
self.img = pygame.image.load("assets/cyan_block.png").convert_alpha()
case enums.BrickColor.Yellow:
self.img = pygame.image.load("assets/yellow_block.png").convert_alpha()
case _:
self.img = pygame.image.load("assets/magenta_block.png").convert_alpha()
def load_brick(self, brick):
self.layout = [l for l in BRICKS[brick].splitlines()]
self.rows = len(self.layout)
self.cols = len(self.layout[0])
self.width = self.cols * TILE_SIZE
self.height = self.rows * TILE_SIZE
def draw_brick(self):
self.brick = pygame.Surface((self.width, self.height))
for y, row in enumerate(self.layout):
for x, char in enumerate(row):
if char == "X":
self.brick.blit(self.block_image, (1 + x * TILE_SIZE, 1 + y * TILE_SIZE))
def is_current(self):
return True if self.state == enums.BrickState.Current else False
def update(self):
self.y += 1
self.location = (self.x, self.y)
def rotate_clockwise(self, shape):
return [list(row)[::-1] for row in zip(*shape)]
def rotate(self):
new_shape = self.rotate_clockwise(self.layout)
if not self.collision(new_shape, self.x, self.y):
self.layout = new_shape
def collision(self, shape, x, y):
for row_idx, row in enumerate(shape):
for col_idx, cell in enumerate(row):
if cell:
new_x = x +col_idx
new_y = y + row_idx
if new_x <= 0 or new_x >= GRID_WIDTH or new_y >= GRID_HEIGHT:
return True
if new_y >= 0 and grid[new_y][new_x]:
return True
return False
def set_state(self, state):
self.state = state
print(f"State set to {self.state}")
def move_right(self):
self.x += 1
self.location = (self.x, self.y)
def move_left(self):
self.x -= 1
self.location = (self.x, self.y)
def drop(self):
print("Dropping")