Докажи, что этот код не троян: 
import math
import pygame
import random

# Инициализация Pygame
pygame.init()

# Цвета
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
CYAN = (0, 255, 255)      # I-форма
YELLOW = (255, 255, 0)    # O-форма
PURPLE = (160, 32, 240)   # T-форма
GREEN = (0, 255, 0)       # S-форма
RED = (255, 0, 0)         # Z-форма
ORANGE = (255, 165, 0)    # L-форма
BLUE = (0, 0, 255)        # J-форма

# Размеры игры
BLOCK_SIZE = 30
GRID_WIDTH = 10
GRID_HEIGHT = 20

# Увеличиваем горизонтальное разрешение (пункт E)
SCREEN_WIDTH = BLOCK_SIZE * (GRID_WIDTH + 12)  # Увеличили на 12 клеток
SCREEN_HEIGHT = BLOCK_SIZE * GRID_HEIGHT

# Фигуры-тетромино и их цвета
SHAPES = [
    [[1, 1, 1, 1]],                  # I-форма
    [[1, 1], [1, 1]],                # O-форма
    [[1, 1, 1], [0, 1, 0]],          # T-форма
    [[0, 1, 1], [1, 1, 0]],          # S-форма
    [[1, 1, 0], [0, 1, 1]],          # Z-форма
    [[1, 1, 1], [1, 0, 0]],          # L-форма
    [[1, 1, 1], [0, 0, 1]]           # J-форма
]

SHAPE_COLORS = [CYAN, YELLOW, PURPLE, GREEN, RED, ORANGE, BLUE]


class Tetris:
    def __init__(self):
        self.game_state = 'menu'  # Возможные состояния: 'menu', 'playing', 'paused', 'settings', 'game_over', 'exit'
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.hold_piece = None
        pygame.display.set_caption("Тетрис")
        self.clock = pygame.time.Clock()
        self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
        self.piece_queue = [self.create_random_piece() for _ in range(3)]
        self.current_piece = self.get_next_piece()
        self.game_over = False
        self.score = 0
        self.total_lines_cleared = 0  # Общее число удаленных линий
        self.fall_speed = 0.5  # Начальная скорость падения
        self.restart_button_rect = None  # Для кнопки перезапуска
        self.settings_button_rect = None  # Для кнопки настроек
        self.buttons = []  # Список кнопок для мобильных устройств
        self.hold_used = False  # Ограничение на использование резерва
        self.button_sizes = {
            'влево': 50,
            'вниз': 50,
            'вправо': 50,
            'поворота': 50,
            'резерв': 50  # Переименовали для удобства (пункт F)
        }
        self.dragging_slider = None  # Для отслеживания перетаскивания ползунка
        self.is_paused = False  # Для паузы игры при сворачивании (пункт A)
        self.return_to_game = False  # Для возврата в игру после настроек (пункт A)

    def show_menu(self):
        while self.game_state == 'menu':
            self.screen.fill(BLACK)
            font = pygame.font.Font(None, 74)
            title_text = font.render("Тетрис", True, WHITE)
            self.screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, SCREEN_HEIGHT // 4))

            # Кнопка "Начать игру"
            button_font = pygame.font.Font(None, 50)
            button_text = button_font.render("Начать игру", True, WHITE)
            button_rect = button_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))

            pygame.draw.rect(self.screen, WHITE, button_rect.inflate(20, 20), 2)
            self.screen.blit(button_text, button_rect)

            # Кнопка "Настройки"
            settings_text = button_font.render("Настройки", True, WHITE)
            settings_rect = settings_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 80))
            pygame.draw.rect(self.screen, WHITE, settings_rect.inflate(20, 20), 2)
            self.screen.blit(settings_text, settings_rect)

            pygame.display.flip()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game_state = 'exit'
                    self.game_over = True
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if button_rect.collidepoint(event.pos):
                        self.game_state = 'playing'
                    if settings_rect.collidepoint(event.pos):
                        self.game_state = 'settings'
                        self.return_to_game = False  # Приход из меню (пункт A)
                        self.show_settings()

            self.clock.tick(60)

    def show_settings(self):
        # Если игра в состоянии 'playing', мы должны заморозить ее (пункт A)
        if self.game_state == 'playing':
            self.is_paused = True
            self.return_to_game = True  # Помним, что нужно вернуться в игру
        settings = True
        while settings:
            self.screen.fill(BLACK)
            font = pygame.font.Font(None, 50)
            title_text = font.render("Настройки", True, WHITE)
            self.screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, 50))

            button_font = pygame.font.Font(None, 36)
            y_offset = 150
            sliders = []
            for name in self.button_sizes:
                text = button_font.render(f"Размер кнопки {name}: {self.button_sizes[name]}", True, WHITE)
                self.screen.blit(text, (50, y_offset))
                slider_rect = pygame.Rect(50, y_offset + 30, 400, 10)
                pygame.draw.rect(self.screen, WHITE, slider_rect)
                handle_x = 50 + int((self.button_sizes[name] - 30) / 50 * slider_rect.width)  # Корректируем для макс. 80
                handle_rect = pygame.Rect(handle_x - 5, y_offset + 25, 10, 20)
                pygame.draw.rect(self.screen, WHITE, handle_rect)
                sliders.append((name, slider_rect, handle_rect))
                y_offset += 70

            back_text = button_font.render("Назад", True, WHITE)
            back_rect = back_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT - 80))
            pygame.draw.rect(self.screen, WHITE, back_rect.inflate(20, 20), 2)
            self.screen.blit(back_text, back_rect)

            pygame.display.flip()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game_state = 'exit'
                    self.game_over = True
                    settings = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if back_rect.collidepoint(event.pos):
                        if self.return_to_game:  # Если пришли из игры
                            self.is_paused = False
                            self.game_state = 'playing'
                        else:
                            self.game_state = 'menu'
                        settings = False
                    for name, slider_rect, handle_rect in sliders:
                        if slider_rect.collidepoint(event.pos) or handle_rect.collidepoint(event.pos):
                            self.dragging_slider = (name, slider_rect)
                            # Изменяем размер кнопки при нажатии
                            pos_x = event.pos[0]
                            new_size = max(30, min(80, int((pos_x - slider_rect.x) / slider_rect.width * 50 + 30)))
                            self.button_sizes[name] = new_size
                            self.create_mobile_buttons()  # Пересоздаем кнопки с новым размером
                elif event.type == pygame.MOUSEBUTTONUP:
                    self.dragging_slider = None
                elif event.type == pygame.MOUSEMOTION and self.dragging_slider:
                    name, slider_rect = self.dragging_slider
                    pos_x = event.pos[0]
                    new_size = max(30, min(80, int((pos_x - slider_rect.x) / slider_rect.width * 50 + 30)))
                    self.button_sizes[name] = new_size
                    self.create_mobile_buttons()  # Пересоздаем кнопки с новым размером

            self.clock.tick(60)

    def create_random_piece(self, index=None):
        if index is None:
            index = random.randint(0, len(SHAPES) - 1)
        shape = SHAPES[index]
        color = SHAPE_COLORS[index]
        return {
            'shape': shape,
            'color': color,
            'x': 0,
            'y': 0
        }

    def get_next_piece(self):
        next_piece = self.piece_queue.pop(0)
        next_piece['x'] = GRID_WIDTH // 2 - len(next_piece['shape'][0]) // 2
        next_piece['y'] = 0
        self.piece_queue.append(self.create_random_piece())
        self.hold_used = False  # Сброс использования резерва при появлении новой фигуры
        return next_piece

    def valid_move(self, piece, x, y):
        for i, row in enumerate(piece['shape']):
            for j, cell in enumerate(row):
                if cell:
                    if (x + j < 0 or x + j >= GRID_WIDTH or
                            y + i >= GRID_HEIGHT or
                            self.grid[y + i][x + j]):
                        return False
        return True

    def place_piece(self, piece):
        for i, row in enumerate(piece['shape']):
            for j, cell in enumerate(row):
                if cell:
                    self.grid[piece['y'] + i][piece['x'] + j] = piece['color']
        self.hold_used = False  # Разрешаем использование резерва (пункт F)

    def remove_complete_lines(self):
        lines_cleared = 0
        new_grid = []
        for row in self.grid:
            if not all(row):
                new_grid.append(row)
            else:
                lines_cleared += 1
        for _ in range(lines_cleared):
            new_grid.insert(0, [0 for _ in range(GRID_WIDTH)])
        self.grid = new_grid
        self.score += lines_cleared * 100
        self.total_lines_cleared += lines_cleared

        # Ускорение игры на 1,005x за каждую удаленную линию
        for _ in range(lines_cleared):
            self.fall_speed /= 1.005

    def rotate_piece(self, piece):
        return {
            'shape': [list(row) for row in zip(*reversed(piece['shape']))],
            'color': piece['color'],
            'x': piece['x'],
            'y': piece['y']
        }

    def draw_next_pieces(self):
        font = pygame.font.Font(None, 24)
        next_text = font.render("Следующие фигуры:", True, WHITE)  # Обновили текст (пункт B)
        next_text_rect = next_text.get_rect()
        x_position = GRID_WIDTH * BLOCK_SIZE + 10
        max_x_position = SCREEN_WIDTH - next_text_rect.width - 10
        if x_position > max_x_position:
            x_position = max_x_position
        self.screen.blit(next_text, (x_position, 150))

        for index, piece in enumerate(self.piece_queue[:2]):
            for i, row in enumerate(piece['shape']):
                for j, cell in enumerate(row):
                    if cell:
                        pygame.draw.rect(
                            self.screen,
                            piece['color'],
                            (x_position + j * BLOCK_SIZE,
                             180 + index * 100 + i * BLOCK_SIZE,
                             BLOCK_SIZE, BLOCK_SIZE)
                        )
                        pygame.draw.rect(
                            self.screen,
                            WHITE,
                            (x_position + j * BLOCK_SIZE,
                             180 + index * 100 + i * BLOCK_SIZE,
                             BLOCK_SIZE, BLOCK_SIZE), 1
                        )

    def hold_piece_swap(self):
        if self.hold_used:
            return  # Если уже использовали резерв, ничего не делаем (пункт F)
        # Если резерв пуст, просто перемещаем текущую фигуру в резерв
        if self.hold_piece is None:
            self.hold_piece = self.current_piece
            self.current_piece = self.get_next_piece()
        else:
            # Если резерв не пуст, меняем текущую и резервную фигуры местами
            self.current_piece, self.hold_piece = self.hold_piece, self.current_piece
            self.current_piece['x'] = GRID_WIDTH // 2 - len(self.current_piece['shape'][0]) // 2
            self.current_piece['y'] = 0
        self.hold_used = True  # Помечаем, что резерв использован

    def draw_hold_piece(self):
        font = pygame.font.Font(None, 36)
        hold_text = font.render("Резерв:", True, WHITE)
        self.screen.blit(hold_text, (GRID_WIDTH * BLOCK_SIZE + 10, 10))

        if self.hold_piece is not None:
            for i, row in enumerate(self.hold_piece['shape']):
                for j, cell in enumerate(row):
                    if cell:
                        pygame.draw.rect(
                            self.screen,
                            self.hold_piece['color'],
                            (GRID_WIDTH * BLOCK_SIZE + 10 + j * BLOCK_SIZE,
                             40 + i * BLOCK_SIZE,
                             BLOCK_SIZE, BLOCK_SIZE)
                        )
                        pygame.draw.rect(
                            self.screen,
                            WHITE,
                            (GRID_WIDTH * BLOCK_SIZE + 10 + j * BLOCK_SIZE,
                             40 + i * BLOCK_SIZE,
                             BLOCK_SIZE, BLOCK_SIZE), 1
                        )

    def draw_grid(self):
        # Рисуем сетку и линии
        for y, row in enumerate(self.grid):
            for x, color in enumerate(row):
                if color:
                    pygame.draw.rect(self.screen, color, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
                    pygame.draw.rect(self.screen, WHITE, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)
        # Рисуем белую полосу справа впритык к игровому полю
        pygame.draw.line(self.screen, WHITE, (GRID_WIDTH * BLOCK_SIZE, 0),
                         (GRID_WIDTH * BLOCK_SIZE, SCREEN_HEIGHT), 2)

    def draw_piece(self, piece):
        for i, row in enumerate(piece['shape']):
            for j, cell in enumerate(row):
                if cell:
                    pygame.draw.rect(self.screen, piece['color'],
                                     ((piece['x'] + j) * BLOCK_SIZE, (piece['y'] + i) * BLOCK_SIZE, BLOCK_SIZE,
                                      BLOCK_SIZE))
                    pygame.draw.rect(self.screen, WHITE,
                                     ((piece['x'] + j) * BLOCK_SIZE, (piece['y'] + i) * BLOCK_SIZE, BLOCK_SIZE,
                                      BLOCK_SIZE), 1)

    def draw_score(self):
        font = pygame.font.Font(None, 24)
        score_text = font.render(f"Количество очков: {self.score}", True, WHITE)
        # Создаем поверхность с прозрачностью
        text_surface = pygame.Surface(score_text.get_size(), pygame.SRCALPHA)
        text_surface.blit(score_text, (0, 0))
        text_surface.set_alpha(150)
        self.screen.blit(text_surface, (10, 10))

    def show_game_over(self):
        self.screen.fill(BLACK)
        font = pygame.font.Font(None, 74)
        game_over_text = font.render("Игра окончена", True, RED)
        self.screen.blit(
            game_over_text,
            (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2,
             SCREEN_HEIGHT // 2 - game_over_text.get_height() // 2)
        )
        pygame.display.flip()
        pygame.time.delay(1500)
        self.reset_game()
        self.game_state = 'menu'

    def reset_game(self):
        self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
        self.piece_queue = [self.create_random_piece() for _ in range(3)]
        self.current_piece = self.get_next_piece()
        self.score = 0
        self.total_lines_cleared = 0
        self.hold_piece = None
        self.hold_used = False
        self.fall_speed = 0.5  # Сброс скорости падения
        self.is_paused = False  # Сброс паузы

    def create_mobile_buttons(self):
        # Создаем кнопки для управления на мобильных устройствах
        gap = 10
        max_button_height = max(self.button_sizes.values())
        total_height = (max_button_height + gap) * 2  # Для двух рядов кнопок
        y_position = SCREEN_HEIGHT - total_height

        # Фиксируем базовую позицию x
        base_x = GRID_WIDTH * BLOCK_SIZE + 20
        current_x = base_x

        left_size = self.button_sizes['влево']
        down_size = self.button_sizes['вниз']
        right_size = self.button_sizes['вправо']
        rotate_size = self.button_sizes['поворота']
        hold_size = self.button_sizes['резерв']

        # Верхний ряд
        rotate_button = pygame.Rect(current_x, y_position, rotate_size, rotate_size)
        current_x += rotate_size + gap

        # Отображаем кнопку резерва только если она доступна (пункт F)
        if not self.hold_used:
            hold_button = pygame.Rect(current_x, y_position, hold_size, hold_size)
            current_x += hold_size + gap
            self.buttons = [('поворота', rotate_button), ('резерв', hold_button)]
        else:
            self.buttons = [('поворота', rotate_button)]

        # Сброс x для нижнего ряда
        current_x = base_x
        y_position += max_button_height + gap

        left_button = pygame.Rect(current_x, y_position, left_size, left_size)
        current_x += left_size + gap
        down_button = pygame.Rect(current_x, y_position, down_size, down_size)
        current_x += down_size + gap
        right_button = pygame.Rect(current_x, y_position, right_size, right_size)

        self.buttons += [
            ('влево', left_button),
            ('вниз', down_button),
            ('вправо', right_button),
        ]

        # Кнопка перезапуска (пункт C)
        gap_top = 10
        self.restart_button_rect = pygame.Rect(SCREEN_WIDTH - 50 - gap_top, gap_top, 40, 40)
        self.settings_button_rect = pygame.Rect(SCREEN_WIDTH - 50 - gap_top, 60 + gap_top, 40, 40)

    def draw_mobile_buttons(self):
        for name, rect in self.buttons:
            pygame.draw.rect(self.screen, WHITE, rect, 2)
            font = pygame.font.SysFont('Arial', int(rect.width * 0.4))
            if name == 'влево':
                self.draw_left_arrow(rect)
            elif name == 'вправо':
                self.draw_right_arrow(rect)
            elif name == 'вниз':
                self.draw_down_arrow(rect)
            elif name == 'поворота':
                self.draw_rotate_icon(rect)
            elif name == 'резерв':
                self.draw_hold_icon(rect, self.hold_piece is not None)
            else:
                text = font.render(name, True, WHITE)
                text_rect = text.get_rect(center=rect.center)
                self.screen.blit(text, text_rect)

        # Кнопка перезапуска (пункты C и D)
        pygame.draw.rect(self.screen, WHITE, self.restart_button_rect, 2)
        self.draw_restart_icon(self.restart_button_rect)
        # Кнопка настроек (пункты C и D)
        pygame.draw.rect(self.screen, WHITE, self.settings_button_rect, 2)
        self.draw_settings_icon(self.settings_button_rect)

    def draw_left_arrow(self, rect):
        x, y, w, h = rect
        points = [
            (x + w * 0.7, y + h * 0.2),
            (x + w * 0.3, y + h * 0.5),
            (x + w * 0.7, y + h * 0.8),
        ]
        pygame.draw.polygon(self.screen, WHITE, points)

    def draw_right_arrow(self, rect):
        x, y, w, h = rect
        points = [
            (x + w * 0.3, y + h * 0.2),
            (x + w * 0.7, y + h * 0.5),
            (x + w * 0.3, y + h * 0.8),
        ]
        pygame.draw.polygon(self.screen, WHITE, points)

    def draw_down_arrow(self, rect):
        x, y, w, h = rect
        points = [
            (x + w * 0.2, y + h * 0.3),
            (x + w * 0.5, y + h * 0.7),
            (x + w * 0.8, y + h * 0.3),
        ]
        pygame.draw.polygon(self.screen, WHITE, points)

    def draw_rotate_icon(self, rect):
        x, y, w, h = rect
        # Рисуем круговую стрелку
        pygame.draw.arc(self.screen, WHITE, (x + w * 0.2, y + h * 0.2, w * 0.6, h * 0.6),
                        math.pi / 4, 2 * math.pi, 2)
        # Рисуем стрелку
        arrow_points = [
            (x + w * 0.7, y + h * 0.25),
            (x + w * 0.8, y + h * 0.35),
            (x + w * 0.6, y + h * 0.35),
        ]
        pygame.draw.polygon(self.screen, WHITE, arrow_points)

    def draw_hold_icon(self, rect, is_open):
        x, y, w, h = rect
        # Рисуем нижнюю часть коробки
        pygame.draw.rect(self.screen, WHITE, (x + w * 0.2, y + h * 0.4, w * 0.6, h * 0.4), 2)
        if is_open:
            # Рисуем открытую крышку
            pygame.draw.polygon(self.screen, WHITE, [
                (x + w * 0.2, y + h * 0.4),
                (x + w * 0.5, y + h * 0.2),
                (x + w * 0.8, y + h * 0.4)
            ], 2)
        else:
            # Рисуем закрытую крышку
            pygame.draw.rect(self.screen, WHITE, (x + w * 0.2, y + h * 0.2, w * 0.6, h * 0.2), 2)

    def draw_restart_icon(self, rect):
        x, y, w, h = rect
        # Рисуем круговую стрелку (символ перезапуска)
        pygame.draw.arc(self.screen, WHITE, (x + w * 0.15, y + h * 0.15, w * 0.7, h * 0.7),
                        0.5 * math.pi, 2 * math.pi, 2)
        # Рисуем стрелку
        arrow_points = [
            (x + w * 0.68, y + h * 0.17),
            (x + w * 0.85, y + h * 0.17),
            (x + w * 0.77, y + h * 0.36),
        ]
        pygame.draw.polygon(self.screen, WHITE, arrow_points)

    def draw_settings_icon(self, rect):
        x, y, w, h = rect
        # Рисуем иконку шестеренки для настроек
        center = (x + w / 2, y + h / 2)
        radius = w * 0.25
        inner_radius = radius * 0.6

        for angle in range(0, 360, 45):
            rad = math.radians(angle)
            start_x = center[0] + inner_radius * math.cos(rad)
            start_y = center[1] + inner_radius * math.sin(rad)
            end_x = center[0] + radius * math.cos(rad)
            end_y = center[1] + radius * math.sin(rad)
            pygame.draw.line(self.screen, WHITE, (start_x, start_y), (end_x, end_y), 2)

        pygame.draw.circle(self.screen, WHITE, center, inner_radius, 2)

    def run(self):
        self.create_mobile_buttons()  # Создаем кнопки для мобильных устройств
        fall_time = 0
        key_down_pressed = False
        down_key_timer = 0

        while not self.game_over:
            if self.game_state == 'menu':
                self.show_menu()
                continue  # Возвращаемся в начало цикла после меню
            elif self.game_state == 'playing':
                pass  # Логика игры будет здесь
            elif self.game_state == 'paused':
                pygame.time.wait(100)  # Ждем, но не занимаем процессор
                continue
            elif self.game_state == 'game_over':
                self.show_game_over()
                continue  # Возвращаемся в начало цикла после экрана окончания игры
            elif self.game_state == 'exit':
                break  # Выходим из основного цикла

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game_over = True
                elif event.type == pygame.WINDOWMINIMIZED:
                    # Игра останавливается, когда свёрнута (пункт A)
                    self.is_paused = True
                elif event.type == pygame.WINDOWRESTORED:
                    # Возобновляем игру при восстановлении окна
                    self.is_paused = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        if self.valid_move(self.current_piece, self.current_piece['x'] - 1, self.current_piece['y']):
                            self.current_piece['x'] -= 1
                    if event.key == pygame.K_RIGHT:
                        if self.valid_move(self.current_piece, self.current_piece['x'] + 1, self.current_piece['y']):
                            self.current_piece['x'] += 1
                    if event.key == pygame.K_DOWN:
                        key_down_pressed = True
                        down_key_timer = 0  # Начинаем отсчет времени
                        if self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y'] + 1):
                            self.current_piece['y'] += 1
                    if event.key == pygame.K_UP:
                        rotated_piece = self.rotate_piece(self.current_piece)
                        if self.valid_move(rotated_piece, rotated_piece['x'], rotated_piece['y']):
                            self.current_piece = rotated_piece
                    if event.key == pygame.K_c:
                        if not self.hold_used:
                            self.hold_piece_swap()
                    if event.key == pygame.K_r:
                        self.reset_game()
                    if event.key == pygame.K_ESCAPE:
                        # Открываем настройки при нажатии ESC
                        self.game_state = 'settings'
                        self.return_to_game = True  # Возвращаемся в игру (пункт A)
                        self.is_paused = True
                        self.show_settings()
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_DOWN:
                        key_down_pressed = False
                        down_key_timer = 0

                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = event.pos
                    for name, rect in self.buttons:
                        if rect.collidepoint(pos):
                            if name == 'влево':
                                if self.valid_move(self.current_piece, self.current_piece['x'] - 1,
                                                   self.current_piece['y']):
                                    self.current_piece['x'] -= 1
                            if name == 'вправо':
                                if self.valid_move(self.current_piece, self.current_piece['x'] + 1,
                                                   self.current_piece['y']):
                                    self.current_piece['x'] += 1
                            if name == 'вниз':
                                if self.valid_move(self.current_piece, self.current_piece['x'],
                                                   self.current_piece['y'] + 1):
                                    self.current_piece['y'] += 1
                            if name == 'поворота':
                                rotated_piece = self.rotate_piece(self.current_piece)
                                if self.valid_move(rotated_piece, rotated_piece['x'], rotated_piece['y']):
                                    self.current_piece = rotated_piece
                            if name == 'резерв':
                                if not self.hold_used:
                                    self.hold_piece_swap()
                    if self.restart_button_rect.collidepoint(pos):
                        self.reset_game()
                    if self.settings_button_rect.collidepoint(pos):
                        self.game_state = 'settings'
                        self.return_to_game = True  # Возвращаемся в игру (пункт A)
                        self.is_paused = True
                        self.show_settings()

            if self.is_paused:
                pygame.time.wait(100)  # Ждем, но не занимаем процессор
                continue  # Пропускаем обновление игры, она заморожена

            if key_down_pressed:
                down_key_timer += self.clock.get_time()
                if down_key_timer >= 150:  # После 0.15 секунды
                    if self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y'] + 1):
                        self.current_piece['y'] += 1
                    down_key_timer = 0

            fall_time += self.clock.get_rawtime()
            self.clock.tick()
            # Основная игровая логика
            if fall_time / 1000 > self.fall_speed:
                if self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y'] + 1):
                    self.current_piece['y'] += 1
                else:
                    self.place_piece(self.current_piece)
                    self.remove_complete_lines()
                    self.current_piece = self.get_next_piece()
                    if not self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y']):
                        self.game_state = 'game_over'
                fall_time = 0

            self.screen.fill(BLACK)
            self.draw_grid()
            self.draw_piece(self.current_piece)
            self.draw_score()
            self.draw_next_pieces()  # Отображаем следующие фигуры
            self.draw_hold_piece()   # Отображаем резервную фигуру
            self.draw_mobile_buttons()  # Отображаем кнопки для мобильных устройств
            pygame.display.flip()

        pygame.quit()


if __name__ == "__main__":
    game = Tetris()
    game.run()