import pygame
# Настройки
WIDTH, HEIGHT = 800, 600
PADDLE_W, PADDLE_H = 15, 90
BALL_SIZE = 15
FPS = 60
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
# Объекты (прямоугольники)
player = pygame.Rect(50, HEIGHT//2 - PADDLE_H//2, PADDLE_W, PADDLE_H)
opponent = pygame.Rect(WIDTH - 50 - PADDLE_W, HEIGHT//2 - PADDLE_H//2, PADDLE_W, PADDLE_H)
ball = pygame.Rect(WIDTH//2, HEIGHT//2, BALL_SIZE, BALL_SIZE)
# Скорости
ball_speed = [5, 5]
player_speed = 0
opponent_speed = 5
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Управление игроком
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP: player_speed = -7
if event.key == pygame.K_DOWN: player_speed = 7
if event.type == pygame.KEYUP:
player_speed = 0
# Движение игрока
player.y += player_speed
player.clamp_ip(screen.get_rect()) # Не дает выйти за экран
# Движение "ИИ" (просто слежка за мячом)
if opponent.centery < ball.centery: opponent.y += opponent_speed
if opponent.centery > ball.centery: opponent.y -= opponent_speed
# Движение мяча
ball.x += ball_speed[0]
ball.y += ball_speed[1]
# Отскоки от стен
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_speed[1] *= -1
# Гол (сброс мяча в центр)
if ball.left <= 0 or ball.right >= WIDTH:
ball.center = (WIDTH//2, HEIGHT//2)
ball_speed[0] *= -1
# Столкновения с ракетками
if ball.colliderect(player) or ball.colliderect(opponent):
ball_speed[0] *= -1
# Отрисовка
screen.fill((30, 30, 30))
pygame.draw.rect(screen, (200, 200, 200), player)
pygame.draw.rect(screen, (200, 200, 200), opponent)
pygame.draw.ellipse(screen, (255, 255, 255), ball)
pygame.draw.aaline(screen, (100, 100, 100), (WIDTH//2, 0), (WIDTH//2, HEIGHT))
pygame.display.flip()
clock.tick(FPS)
pygame.quit()