Untitled

 avatar
unknown
plain_text
2 years ago
2.2 kB
4
Indexable
 import pygame
from pygame.locals import *

# Initialize Pygame
pygame.init()

# Set up the game window
WIDTH = 800
HEIGHT = 400
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ping Pong Game")

# Set up colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# Set up the game clock
clock = pygame.time.Clock()

# Set up the paddles
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 60
PADDLE_SPEED = 5

player_paddle = pygame.Rect(0, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
opponent_paddle = pygame.Rect(WIDTH - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)

# Set up the ball
BALL_RADIUS = 10
BALL_SPEED_X = 3
BALL_SPEED_Y = 3

ball = pygame.Rect(WIDTH // 2 - BALL_RADIUS // 2, HEIGHT // 2 - BALL_RADIUS // 2, BALL_RADIUS, BALL_RADIUS)

ball_velocity = pygame.Vector2(BALL_SPEED_X, BALL_SPEED_Y)

# Set up game variables
score_player = 0
score_opponent = 0
font = pygame.font.Font(None, 36)

# Game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

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

    # Update ball position
    ball.x += ball_velocity.x
    ball.y += ball_velocity.y

    # Check for collisions with paddles
    if ball.colliderect(player_paddle) or ball.colliderect(opponent_paddle):
        ball_velocity.x *= -1

    # Check for collisions with walls
    if ball.top <= 0 or ball.bottom >= HEIGHT:
        ball_velocity.y *= -1

    # Check if the ball goes out of bounds
    if ball.left <= 0:
        score_opponent += 1
        ball_velocity.x *= -1
    elif ball.right >= WIDTH:
        score_player += 1
        ball_velocity.x *= -1

    # Clear the window
    WINDOW.fill(BLACK)

    # Draw the paddles and ball
    pygame.draw.rect(WINDOW, WHITE, player_paddle)
   
Editor is loading...