Untitled
unknown
plain_text
6 months ago
2.0 kB
2
Indexable
import pygame import sys # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 600 BALL_RADIUS = 10 PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100 WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Setup the screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Pong") # Paddle and ball positions left_paddle = pygame.Rect(50, (HEIGHT - PADDLE_HEIGHT) // 2, PADDLE_WIDTH, PADDLE_HEIGHT) right_paddle = pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, (HEIGHT - PADDLE_HEIGHT) // 2, PADDLE_WIDTH, PADDLE_HEIGHT) ball = pygame.Rect(WIDTH // 2, HEIGHT // 2, BALL_RADIUS, BALL_RADIUS) # Ball velocity ball_velocity = [5, 5] # Game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Paddle movement keys = pygame.key.get_pressed() if keys[pygame.K_w] and left_paddle.top > 0: left_paddle.y -= 7 if keys[pygame.K_s] and left_paddle.bottom < HEIGHT: left_paddle.y += 7 if keys[pygame.K_UP] and right_paddle.top > 0: right_paddle.y -= 7 if keys[pygame.K_DOWN] and right_paddle.bottom < HEIGHT: right_paddle.y += 7 # Move the ball ball.x += ball_velocity[0] ball.y += ball_velocity[1] # Ball collision with top and bottom if ball.top <= 0 or ball.bottom >= HEIGHT: ball_velocity[1] = -ball_velocity[1] # Ball collision with paddles if ball.colliderect(left_paddle) or ball.colliderect(right_paddle): ball_velocity[0] = -ball_velocity[0] # Reset ball if it goes off the screen if ball.left <= 0 or ball.right >= WIDTH: ball.x = WIDTH // 2 ball.y = HEIGHT // 2 ball_velocity = [5, 5] # Clear the screen screen.fill(BLACK) # Draw paddles and ball pygame.draw.rect(screen, WHITE, left_paddle) pygame.draw.rect(screen, WHITE, right_paddle) pygame.draw.ellipse(screen, WHITE, ball) # Refresh the screen pygame.display.flip() pygame.time.Clock().tick(60)
Editor is loading...
Leave a Comment