Untitled

 avatar
unknown
plain_text
2 years ago
1.4 kB
4
Indexable
import pygame

# Initialize pygame
pygame.init()

# Set screen size
screen = pygame.display.set_mode((800, 600))

# Set title
pygame.display.set_caption("Ping Pong")

# Set ball starting position and velocity
ball_x = 400
ball_y = 300
ball_velocity_x = 5
ball_velocity_y = 5

# Set paddle starting position
paddle_x = 700
paddle_y = 250

# Main game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Move ball
    ball_x += ball_velocity_x
    ball_y += ball_velocity_y

    # Handle ball collision with walls
    if ball_y > 580 or ball_y < 20:
        ball_velocity_y = -ball_velocity_y
    if ball_x > 780:
        ball_velocity_x = -ball_velocity_x

    # Handle ball collision with paddle
    if ball_x < 30 and paddle_y < ball_y < paddle_y + 50:
        ball_velocity_x = -ball_velocity_x

    # Move paddle
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        paddle_y -= 5
    if keys[pygame.K_DOWN]:
        paddle_y += 5

    # Clear screen
    screen.fill((0, 0, 0))

    # Draw ball
    pygame.draw.circle(screen, (255, 255, 255), (ball_x, ball_y), 10)

    # Draw paddle
    pygame.draw.rect(screen, (255, 255, 255), (paddle_x, paddle_y, 20, 50))

    # Update display
    pygame.display.update()

# Quit pygame
pygame.quit()
Editor is loading...