Menu
CoddyTech

Hit and Reset as Methods

Lesson 39 of 41 in Coddy's Make Games with Pygame course.

Two more jobs belong to the ball: bouncing off a paddle and going back to the middle. As methods, the main loop reads like the rules of the game.

def reset(self):
    self.rect.center = (300, 200)
    self.vx = -self.vx

The two paddle tests differ only in which way the ball leaves: right off the left paddle, left off the right one. Pass that as a number, way, 1 or -1, and one method serves both:

ball.hit(left, 1)
ball.hit(right, -1)

Inside, self.vx = way * abs(self.vx) sends the ball that way however it was moving, and the angle shot stays as it was.

challenge icon

Challenge

Hard

Move the paddle hit and the reset into the Ball class.

  1. Write hit(paddle, way): on a collision, self.vx = way * abs(self.vx) and the angle shot.
  2. Write reset(): centre at (300, 200) and flip self.vx.
  3. In the loop, call ball.hit(left, 1), ball.hit(right, -1), and ball.reset() after each point.

Press Play: the game still plays the same. Then Check.

Try it yourself

import pygame


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.vy
        if self.rect.top <= 0 or self.rect.bottom >= 400:
            self.vy = -self.vy

    def draw(self, surface):
        pygame.draw.rect(surface, (255, 196, 0), self.rect)


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 = Ball()
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.move()
        if ball.rect.colliderect(left):
            ball.vx = abs(ball.vx)
            ball.vy = (ball.rect.centery - left.centery) // 6
        if ball.rect.colliderect(right):
            ball.vx = -abs(ball.vx)
            ball.vy = (ball.rect.centery - right.centery) // 6
        if ball.rect.left > 600:
            left_score += 1
            ball.rect.center = (300, 200)
            ball.vx = -ball.vx
            waiting = True
        if ball.rect.right < 0:
            right_score += 1
            ball.rect.center = (300, 200)
            ball.vx = -ball.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)
    ball.draw(screen)
    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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Make Games with Pygame

Practice on your own: Pygame playground