1

lately I've been trying to create a ping pong game with Pygame but I can't seem to figure out why? or how the ball started tracing when I made it a moving object in the game. how can I go about fixing this problem?

import pygame, sys

def ball_ani():
    global speedx, speedy
    ball.x += speedx
    ball.y += speedy

    if ball.top <= 0 or ball.bottom >= h:
        speedy *= -1
    if ball.left <= 0 or ball.right >= w:
        speedx *= -1
    
    if ball.colliderect(player) or ball.colliderect(player2):
        speedx *= -1

pygame.init()
clock = pygame.time.Clock()

w, h = 1000, 500

pygame.display.set_caption('Fut Pong')
win = pygame.display.set_mode((w, h))
win.fill("black")
pygame.draw.line(win, "white", (w//2, 0), (w//2, h), 3)

ball = pygame.Rect(w//2 - 10, h//2 - 10, 20, 20)
player = pygame.Rect(w - 15, h//2 - 50, 10, 100)
player2 = pygame.Rect(5, h//2 - 50, 10, 100)

speedx, speedy = 7, 7

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ball_ani()

    pygame.draw.ellipse(win, "green", ball)
    pygame.draw.rect(win, "white", player)
    pygame.draw.rect(win, "white", player2)

    pygame.display.flip()
    clock.tick(60)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Blueetoo
  • 13
  • 3

1 Answers1

2

You must clear the display in ever frame:

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = Fasle

    ball_ani()

    win.fill("black") # <--- this is missing

    pygame.draw.ellipse(win, "green", ball)
    pygame.draw.rect(win, "white", player)
    pygame.draw.rect(win, "white", player2)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()

The typical PyGame application loop has to:

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • @hc_dev `cleat` is a typo. Compare [`pygame.quit()`](https://www.pygame.org/docs/ref/pygame.html#pygame.quit) and [`sys.exit()`](https://docs.python.org/3/library/sys.html#sys.exit) – Rabbid76 Feb 18 '22 at 20:43
  • 1
    Thanks, for the direction .. will study deeper, just saw my intuition confirmed in [official docs example](https://www.pygame.org/docs/tut/PygameIntro.html?highlight=quit#taste): `if event.type == pygame.QUIT: sys.exit()` (explained as "simply exit the program, pygame will ensure everything is cleanly shutdown."). Learned something new. – hc_dev Feb 18 '22 at 20:52