Skip to content

Pong take one #87

@Sausagewater69

Description

@Sausagewater69

import pygame
import sys

Initialize Pygame

pygame.init()

Constants

WIDTH, HEIGHT = 600, 400
BALL_SPEED = 5
PADDLE_SPEED = 8

Colors

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

Create the screen

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")

Create paddles and ball

player_paddle = pygame.Rect(50, HEIGHT // 2 - 25, 15, 50)
opponent_paddle = pygame.Rect(WIDTH - 65, HEIGHT // 2 - 25, 15, 50)
ball = pygame.Rect(WIDTH // 2 - 10, HEIGHT // 2 - 10, 20, 20)

Set initial ball direction

ball_direction = [1, 1]

Game loop

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

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

# Update ball position
ball.x += BALL_SPEED * ball_direction[0]
ball.y += BALL_SPEED * ball_direction[1]

# Ball collision with walls
if ball.top <= 0 or ball.bottom >= HEIGHT:
    ball_direction[1] *= -1

# Ball collision with paddles
if ball.colliderect(player_paddle) or ball.colliderect(opponent_paddle):
    ball_direction[0] *= -1

# Draw everything on the screen
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, player_paddle)
pygame.draw.rect(screen, WHITE, opponent_paddle)
pygame.draw.ellipse(screen, WHITE, ball)

# Update the display
pygame.display.flip()

# Cap the frame rate
pygame.time.Clock().tick(60)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions