I have the following code
import pygame
def draw_bar(surface, position, size, color_border, color_background, color_health, progress):
pygame.draw.rect(surface, color_background, (*position, *size))
pygame.draw.rect(surface, color_border, (*position, *size), 1)
innerPos = (position[0]+1, position[1]+1)
innerSize = (int((size[0]-2) * progress), size[1]-2)
pygame.draw.rect(surface, color_health, (*innerPos, *innerSize))
class Player:
def __init__(self, image_name, position, window, max_hp):
self.image = pygame.image.load(image_name).convert_alpha()
self.image = pygame.transform.scale(self.image,
(int(self.image.get_width() * 0.5),
int(self.image.get_height() * 0.5)))
self.window = window
self.position = position
self.rect = self.image.get_rect(center=self.position)
self.max_hp = max_hp
self.current_hp = self.max_hp
def draw_health_bar(self, surf):
health_rect = pygame.Rect(0, 0, self.image.get_width(), 10)
health_rect.midbottom = self.rect.centerx, self.rect.top
draw_bar(surf, health_rect.topleft, health_rect.size,
(0, 0, 0), (255, 0, 0), (0, 255, 0), self.current_hp / self.max_hp)
def draw(self):
self.window.fill((0, 0, 0))
self.window.blit(self.image, (self.position[0] - self.image.get_width()/2, self.position[1] - self.image.get_height()/2))
window = pygame.display.set_mode((300, 300))
character = Player('player.png', [150, 150], window, 80)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
damage = int(input('enter number:'))
character.current_hp -= damage
character.draw() #1
character.draw_health_bar(window) #2
pygame.display.flip() #3
When it was executed, I could only see a black window.
If I added the additional lines (#1, #2 and #3) BEFORE the While loop, the drawn images were visible. However, when I entered 10 in the input prompt (thus, current_hp
was reduced to 70), the green bar was not updated (to be narrower to reveal some red background colour). Only when I entered 10 AGAIN in the input prompt (current_hp
was now 60), then the green bar was updated correctly as expected.
... (same as the block of code above)
window = pygame.display.set_mode((300, 300))
character = Player('player.png', [150, 150], window, 80)
character.draw() #1 additional
character.draw_health_bar(window) #2 additional
pygame.display.flip() #3 additional
run = True
while run:
... (same as the block of code above)
Only this arrangement of code would work perfectly as expected.
window = pygame.display.set_mode((300, 300))
character = Player('player.png', [150, 150], window, 80)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
character.draw()
character.draw_health_bar(window)
pygame.display.flip()
damage = int(input('enter number:'))
character.current_hp -= damage
This is so bewildering, I can’t understand it. Can someone please explain to me like I’m 5?