Understanding how to update screen in pygame?

Viewed 197

Hi I'm very new at Python and now I am trying to understand how the basics in pygame work

I wrote I code where I attempted to make a ball goes up a little bit once the Space key is pressed

So this is my code:

import pygame
import sys

def check_events(ball):
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         sys.exit()
      if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
         ball.centery -= 10 

class Ball():
   def __init__(self,screen):
     self.screen=screen
     self.rect=self.screen.get_rect()
    
     self.color=(255,255,255)
     self.centerx = self.rect.centerx
     self.centery = self.rect.centery
     self.radius=20

   def showcircle(self):    
     pygame.draw.circle(self.screen, self.color, (self.centerx,self.centery), self.radius)


 pygame.init()

 screen = pygame.display.set_mode((1000,1000))
 screen.fill((20,20,20))    
 ball=Ball(screen)


while True:
   check_events(ball)
   ball.showcircle()
   pygame.display.update()

The result is this, after pressing the space key several time

example screen shot

My question is why is still showing the previous positions of the ball instead of updating it after pressing the space key again Please, I hope you could help me Thanks in advance

2 Answers

You need to clear the screen on each frame

while True:
   check_events(ball)
   screen.fill((20,20,20))  # clear screen
   ball.showcircle()
   pygame.display.update()

Basically the movement of the ball is leaving a "trail" of every position it has occupied before. Somehow you need to erase the old copy.

There's two ways to approach this issue. A lot of PyGame programs (most?) elect to re-draw the screen from scratch every frame. It's a simple approach, and easily handles moving objects. However this might also be quite computationally heavy, depending on the program.

Another approach, known as "dirty-rectangles" involves re-drawing only the part of the screen that was effected (made "dirty") by the operation you wish to undo. In your case it's removing the old image of the ball (at the previous location). Here you could paint a background-coloured version of the ball, then move & draw the new one. Or perhaps save the pixels of the background "underneath" where the ball will be next. When the ball is moved, it is erased by replacing the background.

Since you say you're just beginning, it's probably easiest just to re-paint the screen from scratch every update. So as @Mike67 answers, for each update fill the entire screen before re-painting the ball at the new position.

Related