Reputation: 31
Im trying to draw a picture in pygame. I keep it open for a set amount of time and there is no user influence. I was wondering how i could make an object appear, disappear and then reappear after a set amount of time while the other shapes remain the way they are for a set amount of time. Im trying to make a rectangle flicker between yellow and black continuously for the time i set the whole code to remain. Can this be done?
ive tried adding
pygame.draw.rect(screen, BLACK, (300, 200, 100, 125)
pygame.display.flip()
pygame.time.wait(1000)
which works however, it changes the rest of the code before this to stay for the same amount of time
Upvotes: 2
Views: 2166
Reputation: 7361
Of course it is possible. Pygame is quite low level: having an object appear and disappear means that you have to draw it on the screen, delete in from the screen, redraw, delete, and so on.
Actually pygame has no function to "delete". To delete, you have to draw something else on top of the shape: the pixels change color to represent the new shape, and the previous is "deleted." So to delete, you usually draw a rectange colored with the background color.
In your case, a flickering rectangle can be achieved by drawing rectangles in alternate colors at the same position each iteration. The following example shows you how to do it:
import sys
import pygame
#some definitions
YELLOW = (255, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
#initial set up
pygame.init()
screen = pygame.display.set_mode((600, 600))
#making the screen white
screen.fill(WHITE)
#drawing a circle
pygame.draw.circle(screen, YELLOW, (120, 120), 100)
counter = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#select color for rectange, each iteration alternate color to make flickering
if counter % 2 == 0:
fl_color = YELLOW
else:
fl_color = BLACK
#drawing the rectangle
pygame.draw.rect(screen, fl_color, (10, 300, 400, 250))
pygame.display.flip()
counter += 1
pygame.time.wait(1000) #in milliseconds
As you can see, the circle remains yellow, since we never draw something new on top of it. The rectangle is flickering at 1 second rate.
Upvotes: 2