Pong Python
Pong Python
import random
# Initialize Pygame
pygame.init()
# Define constants
WIDTH = 800
HEIGHT = 600
BALL_RADIUS = 10
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH // 2
HALF_PAD_HEIGHT = PAD_HEIGHT // 2
BALL_POS = [WIDTH // 2, HEIGHT // 2]
BALL_VEL = [0, 0]
LEFT = False
RIGHT = True
PADDLE_SPEED = 5
SCORE1 = 0
SCORE2 = 0
FONT = pygame.font.Font(None, 36)
def move_up(self):
self.vel = -PADDLE_SPEED
def move_down(self):
self.vel = PADDLE_SPEED
def stop(self):
self.vel = 0
def update(self):
self.y += self.vel
if self.y - HALF_PAD_HEIGHT < 0:
self.y = HALF_PAD_HEIGHT
elif self.y + HALF_PAD_HEIGHT > HEIGHT:
self.y = HEIGHT - HALF_PAD_HEIGHT
self.rect.centery = self.y
def draw(self):
pygame.draw.rect(screen, self.color, self.rect)
def draw(self):
pygame.draw.rect(screen, WHITE, self.rect)
def update(self):
global BALL_POS, BALL_VEL
BALL_POS[0] += BALL_VEL[0]
BALL_POS[1] += BALL_VEL[1]
# Handle ball collisions with the top and bottom of the screen
if BALL_POS[1] <= BALL_RADIUS or BALL_POS[1] >= HEIGHT - BALL_RADIUS:
BALL_VEL[1] = -BALL_VEL[1]