1

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
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
HasanQ
  • 75
  • 1
  • 3
  • 9

2 Answers2

1

You can use the module time and wait for a certain amount of seconds.

import time

start = time.time() # gets current time

while running:
    if time.time() - start > 1: # if its been 1 second
        removehealth()
        start = time.time()

Also to delete the last item in a list, you can do del playerhealth[-1]

The Big Kahuna
  • 2,097
  • 1
  • 6
  • 19
  • maybe im just setting the start time in the wrong spot. I'm doing collision detection with an enemy, i just don't want all my health to disappear the second i touch them. i want it to disappear one heart at a time. This solution just didn't do anything, and nothing happened when i hit an enemy. – HasanQ Apr 06 '20 at 03:24
  • @HasanQ Sorry, i forgot a line, all fixed. Just add the `start = time.time()` so it 'resets'. – The Big Kahuna Apr 06 '20 at 04:42
1

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)).

Rabbid76
  • 202,892
  • 27
  • 131
  • 174