import pygame
import sys
import random
# Инициализация Pygame
pygame.init()
# Настройки окна
WIDTH, HEIGHT = 500, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Движение платформы и мяча")
# FPS
FPS = 40
clock = pygame.time.Clock()
# Цвета
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
RED = (255, 0, 0)
LIGHT_BLUE = (135, 206, 235)
BLACK = (0, 0, 0) # Добавили черный цвет
# Класс платформы
class Platform:
def __init__(self):
self.width = 100
self.height = 15
self.x = WIDTH // 2 - self.width // 2
self.y = HEIGHT - 50
self.speed = 8
self.color = YELLOW
def move_left(self):
self.x = max(0, self.x - self.speed)
def move_right(self):
self.x = min(WIDTH - self.width, self.x + self.speed)
def draw(self):
pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
# Класс мяча
class Ball:
def __init__(self):
self.radius = 20
self.x = WIDTH // 2
self.y = HEIGHT // 2
self.speed_x = random.choice([-4, 4])
self.speed_y = -4
self.color = BLACK # Теперь мяч черный
def move(self):
self.x += self.speed_x
self.y += self.speed_y
if self.x <= self.radius or self.x >= WIDTH - self.radius:
self.speed_x = -self.speed_x
if self.y <= self.radius:
self.speed_y = -self.speed_y
def check_collision_with_platform(self, platform):
if (self.y + self.radius >= platform.y and
self.y - self.radius <= platform.y + platform.height and
self.x >= platform.x and
self.x <= platform.x + platform.width):
self.speed_y = -self.speed_y
if self.x < platform.x + platform.width // 2:
self.speed_x = max(-6, self.speed_x - 1)
else:
self.speed_x = min(6, self.speed_x + 1)
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
# Создание объектов
platform = Platform()
ball = Ball()
# Игровой цикл
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
platform.move_left()
if keys[pygame.K_RIGHT]:
platform.move_right()
ball.move()
ball.check_collision_with_platform(platform)
screen.fill(LIGHT_BLUE)
platform.draw()
ball.draw()
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
sys.exit()