Menu
CoddyTech

The Ball

Lesson 29 of 40 in Coddy's Make Games with Pygame course.

Pong is two paddles and a ball. Start with the ball: a small square that moves by itself.

Its speed has two parts, how far it moves across in a frame and how far down. These are the ball's velocity, often called vx and vy:

ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4

while running:
    # events
    ball.x += vx
    ball.y += vy

With both parts the ball moves on a slant. A negative vx moves it left and a negative vy moves it up. Changing a sign later is how the ball bounces.

vx, vy = 5, 4 sets two variables in one line.

challenge icon

Challenge

Easy
  1. Before the loop, make ball = pygame.Rect(293, 193, 14, 14) and vx, vy = 5, 4.
  2. In the loop, add vx to ball.x and vy to ball.y.
  3. Draw the ball in yellow (255, 196, 0) after the fill.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()

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

    screen.fill((30, 30, 46))
    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