Reputation: 375
Want to change the color of the screen more often. It should be some kind of blinking. This should happen when the button is pressed. But the program runs in an endless loop.
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
timer = pygame.time.Clock()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
bg_active_color = WHITE
screen.fill(WHITE)
CHANGE_COLOR = pygame.USEREVENT + 1
pygame.time.set_timer(CHANGE_COLOR, 500)
counter = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if event.type == CHANGE_COLOR:
counter += 1
if counter < 4:
if bg_active_color == RED:
screen.fill(RED)
bg_active_color = WHITE
elif bg_active_color == WHITE:
screen.fill(WHITE)
bg_active_color = RED
else:
pygame.time.set_timer(CHANGE_COLOR,0)
print("end")
if event.type == pygame.QUIT:
running = False
pygame.display.update()
timer.tick(30)
pygame.quit()
Upvotes: 1
Views: 107
Reputation: 210968
You can not nest the events. You have to test the event type in an if
-elif
-else
statement. Check if LEFT is pressed with the KEYDOWN
event and K_LEFT
key and start the timer. Do not call fill
in the event loop. It is sufficient to change the bg_active_color
variable:
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
timer = pygame.time.Clock()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
bg_active_color = WHITE
CHANGE_COLOR = pygame.USEREVENT + 1
counter = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pygame.time.set_timer(CHANGE_COLOR, 500)
counter = 0
elif event.type == CHANGE_COLOR:
if counter < 4:
if bg_active_color == RED:
bg_active_color = WHITE
elif bg_active_color == WHITE:
bg_active_color = RED
else:
pygame.time.set_timer(CHANGE_COLOR,0)
print("end")
counter += 1
screen.fill(bg_active_color)
pygame.display.update()
timer.tick(30)
pygame.quit()
Upvotes: 1