import pygame # Initialize Pygame pygame.init() # Constants SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 PADDLE_WIDTH = 10 PADDLE_HEIGHT = 100 BALL_RADIUS = 10 WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Create the game window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Two Player Pong") clock = pygame.time.Clock() # Define the Paddle class class Paddle(pygame.sprite.Sprite): def __init__(self, x): super().__init__() self.image = pygame.Surface([PADDLE_WIDTH, PADDLE_HEIGHT]) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.centerx = x self.rect.centery = SCREEN_HEIGHT // 2 self.speed = 0 def update(self): self.rect.y += self.speed if self.rect.top < 0: self.rect.top = 0 elif self.rect.bottom > SCREEN_HEIGHT: self.rect.bottom = SCREEN_HEIGHT # Define the Ball class class Ball(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface([BALL_RADIUS * 2, BALL_RADIUS * 2]) self.image.fill(WHITE) pygame.draw.circle(self.image, BLACK, (BALL_RADIUS, BALL_RADIUS), BALL_RADIUS) self.rect = self.image.get_rect() self.rect.centerx = SCREEN_WIDTH // 2 self.rect.centery = SCREEN_HEIGHT // 2 self.speed_x = 5 self.speed_y = 5 def update(self): self.rect.x += self.speed_x self.rect.y += self.speed_y if self.rect.top <= 0 or self.rect.bottom >= SCREEN_HEIGHT: self.speed_y *= -1 # Create sprites paddle1 = Paddle(20) paddle2 = Paddle(SCREEN_WIDTH - 20) ball = Ball() all_sprites = pygame.sprite.Group() all_sprites.add(paddle1, paddle2, ball) # Main game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_w: paddle1.speed = -5 elif event.key == pygame.K_s: paddle1.speed = 5 elif event.key == pygame.K_UP: paddle2.speed = -5 elif event.key == pygame.K_DOWN: paddle2.speed = 5 elif event.type == pygame.KEYUP: if event.key == pygame.K_w or event.key == pygame.K_s: paddle1.speed = 0 elif event.key == pygame.K_UP or event.key == pygame.K_DOWN: paddle2.speed = 0 all_sprites.update() # Ball-Paddle collision if pygame.sprite.collide_rect(ball, paddle1) or pygame.sprite.collide_rect(ball, paddle2): ball.speed_x *= -1 # Game over condition if ball.rect.left <= 0 or ball.rect.right >= SCREEN_WIDTH: running = False screen.fill(BLACK) all_sprites.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()