import pygame
import random
# Инициализация Pygame
pygame.init()
# Настройки экрана
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Песочница с несколькими объектами")
# Цвета
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Класс для шаров
class Ball:
def __init__(self, x, y, radius, color, speed_x, speed_y):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.speed_x = speed_x
self.speed_y = speed_y
def move(self):
# Обновление позиции шара
self.x += self.speed_x
self.y += self.speed_y
# Отскок от границ экрана
if self.x - self.radius <= 0 or self.x + self.radius >= WIDTH:
self.speed_x *= -1
if self.y - self.radius <= 0 or self.y + self.radius >= HEIGHT:
self.speed_y *= -1
def draw(self, surface):
# Отрисовка шара
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), self.radius)
# Функция для создания нового шара
def create_ball(x=None, y=None):
radius = random.randint(10, 30)
x = x if x is not None else random.randint(radius, WIDTH - radius)
y = y if y is not None else random.randint(radius, HEIGHT - radius)
color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
speed_x = random.choice([-3, -2, -1, 1, 2, 3])
speed_y = random.choice([-3, -2, -1, 1, 2, 3])
return Ball(x, y, radius, color, speed_x, speed_y)
def main():
clock = pygame.time.Clock()
balls = [] # Список для хранения объектов шаров
running = True
# Создаем начальные шары
for _ in range(5):
balls.append(create_ball())
while running:
clock.tick(60) # Ограничение до 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Создание нового шара при нажатии левой кнопки мыши
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Левая кнопка
mouse_x, mouse_y = event.pos
balls.append(create_ball(mouse_x, mouse_y))
# Обновление состояния шаров
for ball in balls:
ball.move()
# Отрисовка
SCREEN.fill(WHITE)
for ball in balls:
ball.draw(SCREEN)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
Не могу понять как заставить несколько объектов с помощью функции.
Заранее спасибо:)