I've tried using threading.timer to solve the issue, but can't seem to get it to work for what i want to do. No error messages. Either it doesn't even subtract from the players health, or it just drains the health instantly defeating the whole point, and time.sleep just freezes the whole program.
Here is the code i can't get to work properly
from threading import Timer
import pygame
playerhealth = ['<3', '<3', '<3', '<3', '<3'] # just a list of player health symbolized by hearts
running = True
while running:
def removehealth():
playerhealth.__delitem__(-1) # deletes the last item in the list of hearts
t = Timer(1, removehealth)
t.start()
# id display the hearts on screen down here
The way to do that using pygame, is to usee pygame.time.set_timer()
to repeatedly create an USEREVENT
. e.g.:
milliseconds_delay = 1000 # 1 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, milliseconds_delay)
In pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT
(24) and pygame.NUMEVENTS
(32). In this case pygame.USEREVENT+1
is the event id for the timer event, which drains the health.
Remove a heart when the event occurs in the event loop:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == timer_event:
del playerhealth[-1]
A timer event can be stopped by passing 0 to the time parameter (pygame.time.set_timer(timer_event, 0)
).