Загрузка данных


import pygame
import sys
import random

# 1. Подключаем игровую библиотеку Pygame
pygame.init()

# 2. Создаём окно игры 500x500
WIDTH, HEIGHT = 500, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Игра: Мяч, Платформа и Монстры")

# 3. Задаём FPS
FPS = 40
clock = pygame.time.Clock()

# 5. Класс Area (из прошлого проекта)
class Area:
    def __init__(self, x=0, y=0, width=10, height=10, color=None):
        self.rect = pygame.Rect(x, y, width, height)
        self.fill_color = color if color else (255, 255, 255)
    
    def color(self, new_color):
        self.fill_color = new_color
    
    def fill(self):
        pygame.draw.rect(screen, self.fill_color, self.rect)
    
    def collidepoint(self, point):
        return self.rect.collidepoint(point)
    
    def colliderect(self, rect):
        return self.rect.colliderect(rect)
    
    def set_position(self, x, y):
        self.rect.x = x
        self.rect.y = y
    
    def position(self):
        return self.rect.x, self.rect.y
    
    def move(self, dx, dy):
        self.rect.x += dx
        self.rect.y += dy

# 6. Класс Picture как наследник Area
class Picture(Area):
    def __init__(self, filename, x=0, y=0, width=10, height=10):
        super().__init__(x, y, width, height)
        self.image = pygame.image.load(filename)
        self.image = pygame.transform.scale(self.image, (width, height))
    
    def draw(self):
        screen.blit(self.image, (self.rect.x, self.rect.y))

# 7. Создаём спрайты: мяч и платформа
# Для демонстрации создадим простые геометрические фигуры, так как файлов с изображениями нет
# Если у вас есть файлы мяча и платформы - раскомментируйте строки с Picture
ball = Picture("ball.png", 240, 300, 20, 20)  # Если есть файл ball.png
# Или используем Area для мяча (как временный вариант)
# ball = Area(240, 300, 20, 20, (255, 0, 0))

platform = Picture("platform.png", 200, 450, 100, 20)  # Если есть файл platform.png
# Или временный вариант
# platform = Area(200, 450, 100, 20, (0, 255, 0))

# Если у вас нет картинок, создадим временные спрайты через Area
# Раскомментируйте этот блок, если нет файлов изображений:
"""
class TemporarySprite(Area):
    def draw(self):
        self.fill()
    def set_image(self, color):
        self.fill_color = color

ball = TemporarySprite(240, 300, 20, 20, (255, 0, 0))
platform = TemporarySprite(200, 450, 100, 20, (0, 255, 0))
"""

# 8. Создаём список из 24 монстров
monsters = []
monster_width, monster_height = 30, 30

# Располагаем монстров в сетке (например, 6x4)
cols, rows = 6, 4
start_x = 50
start_y = 50
spacing_x = (WIDTH - 2 * start_x) / (cols - 1)
spacing_y = 60

for i in range(24):
    row = i // cols
    col = i % cols
    x = start_x + col * spacing_x
    y = start_y + row * spacing_y
    
    # Создаём монстра (если есть файл monster.png)
    try:
        monster = Picture("monster.png", x, y, monster_width, monster_height)
    except:
        # Если нет файла, используем Area с цветом
        monster = Area(x, y, monster_width, monster_height, (128, 0, 128))
        # Добавляем метод draw для единообразия
        monster.draw = lambda: monster.fill()
    
    monsters.append(monster)

# 9. Игровой цикл
running = True
while running:
    # 4. Обработка событий и выход при закрытии окна
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
    
    # Управление платформой (стрелки влево/вправо)
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and platform.rect.x > 0:
        platform.move(-5, 0)
    if keys[pygame.K_RIGHT] and platform.rect.x < WIDTH - platform.rect.width:
        platform.move(5, 0)
    
    # Заполняем фон цветом (например, небесно-голубым)
    screen.fill((135, 206, 235))  # 3. Заливаем сцену цветом
    
    # 7. Отображаем спрайты
    if hasattr(ball, 'draw'):
        ball.draw()
    else:
        ball.fill()
    
    if hasattr(platform, 'draw'):
        platform.draw()
    else:
        platform.fill()
    
    # 9. Отображаем всех монстров
    for monster in monsters:
        if hasattr(monster, 'draw'):
            monster.draw()
        else:
            monster.fill()
    
    # Обновляем экран
    pygame.display.flip()
    
    # Ограничиваем FPS
    clock.tick(FPS)

# Завершаем работу Pygame
pygame.quit()
sys.exit()