Back to the Middle
Part of the Projects section of Coddy's Pygame journey. Lesson 15 of 31.
When a player misses, the ball leaves the window on their side. Bring it back to the middle and send it toward the other side.
if ball.right < 0 or ball.left > 600:
ball.center = (300, 200)
vx = -vxball.right < 0 means the whole ball is past the left edge, and ball.left > 600 the whole ball past the right. Setting ball.center moves the Rect so its middle is at that point; its size stays the same.
The vx = -vx here is safe: the ball is in the middle, far from any paddle.
Challenge
EasyWhen the whole ball is past the left or right edge, set its center to (300, 200) and flip vx.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
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)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = 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())
ball.x += vx
ball.y += vy
if ball.top <= 0 or ball.bottom >= 400:
vy = -vy
if ball.colliderect(left):
vx = abs(vx)
if ball.colliderect(right):
vx = -abs(vx)
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)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Projects
Practice on your own: Pygame playground