I'm creating a game in pygame and I want to decrease the player's HP slowly yet in real time. For this, I know that I can't use time.sleep()
because it freezes the whole game. I've tried using threading.Thread
on pygame.MOUSEBUTTONDOWN
to do an amount of damage to the player, but it did not work. Keep in mind that it is my first time using threads ever.
My code:
#-*- coding-utf8 -*-
import pygame
import threading
import time
import os
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()
SIZE = (1200, 600)
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
class Player:
def __init__(self):
self.HP = 100
self.HP_BAR = pygame.Rect(10, 10, self.HP * 3, 10)
self.X = 100
self.Y = 100
self.WIDTH = 50
self.HEIGHT = 100
self.COLOR = (255,255,0)
self.PLAYER = pygame.Rect(self.X, self.Y, self.WIDTH, self.HEIGHT)
def move(self):
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]: self.Y -= 1
if pressed[pygame.K_s]: self.Y += 1
if pressed[pygame.K_a]: self.X -= 1
if pressed[pygame.K_d]: self.X += 1
self.PLAYER = pygame.Rect(self.X, self.Y, self.WIDTH, self.HEIGHT)
def draw(self):
# clear screen
screen.fill((0,0,0))
# draw HP bar
self.HP_BAR = pygame.Rect(10, 10, self.HP * 3, 10)
pygame.draw.rect(screen, (50,0,0), self.HP_BAR)
# draw player
pygame.draw.rect(screen, self.COLOR, self.PLAYER)
pygame.display.flip()
def remove_HP(self, value):
for x in range(value):
self.HP -= 1
self.draw()
# time.sleep(0.1)
p1 = Player()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
exit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
td2 = threading.Thread(target = p1.remove_HP(20), name = "td2")
td2.daemon = True
td2.start()
p1.move()
p1.draw()
clock.tick(60)
Am I using threads wrong? I want to execute the p1.remove_HP()
and p1.move()
at the same time, but what the program does is:
user clicks while pressing [A]
1º: p1.move()
2º: p1 stops moving
3º: p1.remove_HP()
4º: p1 is moving again
Sorry if it is stupid but I'm really trying and studying. Thanks in advance!