You should use list (or pygame.sprite.Group
) to keep hitboxes with current_time + 200 ms
And in every loop you should check every hitbox on list if it is time to remove it from list.
And later you should draw all hitboxes from list.
Working example:
At start I create empty list
all_items = []
In loop I get
current_time = pygame.time.get_ticks()
When I click mouse button then I add items to this list with remove_at
x, y = event.pos
item = {
'rect': pygame.Rect(x-10, y-10, 20, 20),
'remove_at': current_time + 500, # 500ms = 0.5s
}
all_items.append(item)
Later I use for
-loop to keep only items which have remove_at > current_time
keep_items = []
for item in all_items:
if item['remove_at'] > current_time:
keep_items.append(item)
else:
print('removed:', item)
all_items = keep_items
And later I draw all items from this list:
for item in all_items:
pygame.draw.rect(screen, RED, item['rect'])
Full code:
import pygame
# --- constants --- (UPPER_CASE_NAMES)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 25 # for more than 220 it has no time to update screen
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# --- functions --- (lower_case_names)
# --- main ---
pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
all_items = []
# --- mainloop ---
clock = pygame.time.Clock()
running = True
while running:
current_time = pygame.time.get_ticks()
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
item = {
'rect': pygame.Rect(x-10, y-10, 20, 20),
'remove_at': current_time + 500, # 500ms = 0.5s
}
all_items.append(item)
print("add at:", x, y)
# --- changes/moves/updates ---
# filter objects
keep_items = []
for item in all_items:
if item['remove_at'] > current_time:
keep_items.append(item)
else:
print('removed:', item)
all_items = keep_items
# --- draws ---
screen.fill(BLACK)
for item in all_items:
pygame.draw.rect(screen, RED, item['rect'])
pygame.display.flip()
# --- FPS ---
ms = clock.tick(FPS)
#pygame.display.set_caption('{}ms'.format(ms)) # 40ms for 25FPS, 16ms for 60FPS
fps = clock.get_fps()
pygame.display.set_caption('FPS: {}'.format(fps))
# --- end ---
pygame.quit()