Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.7 kB
1
Indexable
Never
import pygame

# Define constants
WIDTH = 800
HEIGHT = 600
BALL_RADIUS = 10
PAD_WIDTH = 8
PAD_HEIGHT = 80
PADDLE_SPEED = 5
BALL_SPEED = 5

# Initialize pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")

# Set up game objects
ball_pos = [WIDTH//2, HEIGHT//2]
ball_vel = [BALL_SPEED, BALL_SPEED]
paddle1_pos = HEIGHT//2 - PAD_HEIGHT//2
paddle2_pos = HEIGHT//2 - PAD_HEIGHT//2
score1 = 0
score2 = 0

# Define helper functions
def draw_ball(ball_pos):
    pygame.draw.circle(screen, (255, 255, 255), ball_pos, BALL_RADIUS)

def draw_paddle(paddle_pos):
    pygame.draw.rect(screen, (255, 255, 255), (0, paddle_pos, PAD_WIDTH, PAD_HEIGHT))

def update_ball(ball_pos, ball_vel):
    # Update ball position
    ball_pos[0] += ball_vel[0]
    ball_pos[1] += ball_vel[1]

    # Check for collisions with walls
    if ball_pos[1] <= BALL_RADIUS or ball_pos[1] >= HEIGHT - BALL_RADIUS:
        ball_vel[1] = -ball_vel[1]
    if ball_pos[0] <= PAD_WIDTH + BALL_RADIUS:
        if ball_pos[1] >= paddle1_pos and ball_pos[1] <= paddle1_pos + PAD_HEIGHT:
            ball_vel[0] = -ball_vel[0]
        else:
            reset_ball(2)
            return
    if ball_pos[0] >= WIDTH - PAD_WIDTH - BALL_RADIUS:
        if ball_pos[1] >= paddle2_pos and ball_pos[1] <= paddle2_pos + PAD_HEIGHT:
            ball_vel[0] = -ball_vel[0]
        else:
            reset_ball(1)
            return

def update_paddle(paddle_pos, direction):
    # Update paddle position
    if direction == "up":
        paddle_pos -= PADDLE_SPEED
    elif direction == "down":
        paddle_pos += PADDLE_SPEED

    # Check for collisions with walls
    if paddle_pos < 0:
        paddle_pos = 0
    elif paddle_pos > HEIGHT - PAD_HEIGHT:
        paddle_pos = HEIGHT - PAD_HEIGHT

    return paddle_pos

def reset_ball(player):
    global ball_pos, ball_vel, score1, score2
    ball_pos = [WIDTH//2, HEIGHT//2]
    if player == 1:
        ball_vel = [-BALL_SPEED, -BALL_SPEED]
        score2 += 1
    else:
        ball_vel = [BALL_SPEED, BALL_SPEED]
        score1 += 1

# Game loop
running = True
while running:
    # Handle events
    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_pos = update_paddle(paddle1_pos, "up")
            elif event.key == pygame.K_s:
                paddle1_pos = update_paddle(paddle1_pos, "down")
            elif event.key == pygame.K_UP:
                paddle2_pos = update_paddle(paddle2_pos, "up")
            elif event.key == pygame.K_DOWN:
                paddle2