Учебное пособие по игре Pygame Tetris: создайте свою собственную игру тетрис с помощью Pygame

Вот руководство по созданию игры «Тетрис» с использованием библиотеки Pygame на Python:

Шаг 1. Настройка окна игры

import pygame
pygame.init()
# Set up the dimensions of the game window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Pygame Tetris")
# Game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    pygame.display.update()
pygame.quit()

Шаг 2. Создание тетримино (игровых фигур)

class Tetrimino:
    def __init__(self, shape, color):
        self.shape = shape
        self.color = color
        self.x = WINDOW_WIDTH // 2
        self.y = 0
    def draw(self, window):
        for row in range(len(self.shape)):
            for col in range(len(self.shape[row])):
                if self.shape[row][col] == 'X':
                    pygame.draw.rect(window, self.color, (self.x + col * BLOCK_SIZE, self.y + row * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
    def move_down(self):
        self.y += BLOCK_SIZE
    def move_left(self):
        self.x -= BLOCK_SIZE
    def move_right(self):
        self.x += BLOCK_SIZE

Шаг 3. Обработка вводимых пользователем данных

# Inside the game loop
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    tetrimino.move_left()
if keys[pygame.K_RIGHT]:
    tetrimino.move_right()
if keys[pygame.K_DOWN]:
    tetrimino.move_down()

Шаг 4. Рисование игровой сетки и тетримино

# Inside the game loop, before pygame.display.update()
window.fill((0, 0, 0))  # Clear the window
# Draw the game grid
for row in range(GRID_HEIGHT):
    for col in range(GRID_WIDTH):
        pygame.draw.rect(window, (255, 255, 255),
                         (col * BLOCK_SIZE, row * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)
# Draw the current tetrimino
tetrimino.draw(window)
pygame.display.update()

Шаг 5. Добавление обнаружения столкновений и игровой логики

class TetrisGame:
    def __init__(self):
        self.grid = [[None] * GRID_WIDTH for _ in range(GRID_HEIGHT)]
        self.current_tetrimino = Tetrimino(random.choice(TETRIMINO_SHAPES), random.choice(TETRIMINO_COLORS))
    def update(self):
        if self.can_move_down():
            self.current_tetrimino.move_down()
        else:
            self.lock_tetrimino()
            self.clear_lines()
    def can_move_down(self):
        for row in range(len(self.current_tetrimino.shape)):
            for col in range(len(self.current_tetrimino.shape[row])):
                if self.current_tetrimino.shape[row][col] == 'X':
                    next_row = self.current_tetrimino.y // BLOCK_SIZE + row + 1
                    if next_row >= GRID_HEIGHT or self.grid[next_row][col + self.current_tetrimino.x // BLOCK_SIZE] is not None:
                        return False
        return True
    def lock_tetrimino(self):
        for row in range(len(self.current_tetrimino.shape)):
            for col in range(len(self.current_tetrimino.shape[row])):
                if self.current_tetrimino.shape[row][col] == 'X':
                    self.grid[self.current_tetrimino.y // BLOCK_SIZE + row][col + self.current_tetrimino.x // BLOCK_SIZE] = self.current_tetrimino.color
        self.current_tetrimino = Tetrimino(random.choice(TETRIMINO_SHAPES), random.choice(TETRIMINO_COLORS))
    def clear_lines(self):
        full_rows = []
        for row in range(GRID_HEIGHT):
            if all(cell is not None for cell in self.grid[row]):
                full_rows.append(row)
        for row in full_rows:
            del self.grid[row]
            self.grid.insert(0, [None] * GRID_WIDTH)

Шаг 6. Запуск игры

# Outside the game loop
game = TetrisGame()
clock = pygame.time.Clock()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    game.update()
    window.fill((0, 0, 0))
    game.draw(window)
    pygame.display.update()
    clock.tick(10)
pygame.quit()