A Ball Class
Lesson 38 of 40 in Coddy's Make Games with Pygame course.
The ball is a Rect plus two numbers, and four jobs: move, hit a paddle, reset, draw. A class keeps data and the functions that use it together:
class Ball:
def __init__(self):
self.rect = pygame.Rect(293, 193, 14, 14)
self.vx = 5
self.vy = 4
def move(self):
self.rect.x += self.vx
self.rect.y += self.vyball = Ball() makes a ball object and runs __init__. Inside the class, self is the object, so self.vx is this ball's own vx. Functions in a class are methods: ball.move() calls one.
The main loop then reads like the rules of the game: ball.move(), ball.hit(left, 1), ball.hit(right, -1), ball.reset(), ball.draw(screen). The game plays the same as before.
Challenge
HardRewrite the ball as a class Ball at the top of the file, with:
__init__:self.rect,self.vx = 5,self.vy = 4move(): moves and bounces off the top and bottomhit(paddle, way): on a collision,self.vx = way * abs(self.vx)and the angle shotreset(): back to the middle,vxflippeddraw(surface)
Make ball = Ball() and use its methods in the loop. Replace ball.left with ball.rect.left and so on. The game must play the same.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
left_score = 0
right_score = 0
waiting = False
winner = None
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
if winner is None:
waiting = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
left.y -= 6
if keys[pygame.K_s]:
left.y += 6
if keys[pygame.K_UP]:
right.y -= 6
if keys[pygame.K_DOWN]:
right.y += 6
left.clamp_ip(screen.get_rect())
right.clamp_ip(screen.get_rect())
if not waiting:
ball.x += vx
ball.y += vy
if ball.top <= 0 or ball.bottom >= 400:
vy = -vy
if ball.colliderect(left):
vx = abs(vx)
vy = (ball.centery - left.centery) // 6
if ball.colliderect(right):
vx = -abs(vx)
vy = (ball.centery - right.centery) // 6
if ball.left > 600:
left_score += 1
ball.center = (300, 200)
vx = -vx
waiting = True
if ball.right < 0:
right_score += 1
ball.center = (300, 200)
vx = -vx
waiting = True
if left_score == 5:
winner = "Left player wins!"
elif right_score == 5:
winner = "Right player wins!"
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), left)
pygame.draw.rect(screen, (235, 80, 80), right)
pygame.draw.rect(screen, (255, 196, 0), ball)
score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
screen.blit(score, score.get_rect(center=(300, 30)))
if winner is not None:
message = font.render(winner, True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(300, 120)))
elif waiting:
message = font.render("Press Space to serve", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(300, 360)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Make Games with Pygame
1The Game Loop
Open a WindowFill the Background4Two Players and a Ball
The BallBouncePractice on your own: Pygame playground