create a pong game in python

To create a Pong game in Python, we can use the pygame module. Here is a simple implementation:

main.py
import pygame
pygame.init()

# Set up the game screen
WIDTH, HEIGHT = 700, 500
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")

# Set up the game elements
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
PADDLE_SPEED = 5
BALL_WIDTH, BALL_HEIGHT = 10, 10
BALL_SPEED_X, BALL_SPEED_Y = 5, 5

paddle1 = pygame.Rect(50, 200, PADDLE_WIDTH, PADDLE_HEIGHT)
paddle2 = pygame.Rect(WIDTH - 60, 200, PADDLE_WIDTH, PADDLE_HEIGHT)
ball = pygame.Rect(WIDTH//2 - BALL_WIDTH//2, HEIGHT//2 - BALL_HEIGHT//2, BALL_WIDTH, BALL_HEIGHT)

# Game loop
while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Move player paddles
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w] and paddle1.top > 0:
        paddle1.top -= PADDLE_SPEED
    if keys[pygame.K_s] and paddle1.bottom < HEIGHT:
        paddle1.bottom += PADDLE_SPEED
    if keys[pygame.K_UP] and paddle2.top > 0:
        paddle2.top -= PADDLE_SPEED
    if keys[pygame.K_DOWN] and paddle2.bottom < HEIGHT:
        paddle2.bottom += PADDLE_SPEED

    # Move ball
    ball.left += BALL_SPEED_X
    ball.top += BALL_SPEED_Y
 
    # Check for wall collisions
    if ball.top <= 0 or ball.bottom >= HEIGHT:
        BALL_SPEED_Y *= -1
    if ball.left <= 0 or ball.right >= WIDTH:
        BALL_SPEED_X *= -1
 
    # Check for paddle collisions
    if ball.colliderect(paddle1) or ball.colliderect(paddle2):
        BALL_SPEED_X *= -1
 
    # Draw game elements
    SCREEN.fill((0, 0, 0))
    pygame.draw.rect(SCREEN, (255, 255, 255), paddle1)
    pygame.draw.rect(SCREEN, (255, 255, 255), paddle2)
    pygame.draw.ellipse(SCREEN, (255, 255, 255), ball)
    pygame.display.flip()
1751 chars
58 lines

This code creates a basic Pong game with two paddles and a ball. The paddles are controlled by the player using the W, S, UP, and DOWN keys. The ball bounces off the walls and the paddles, and the game ends when the ball goes off the screen. This is just a starting point, and you can add more features to make the game more interesting.

gistlibby LogSnag