问题
I have a progress bar in the code which only shows a GREEN color but i want to modify it with the percentage of a player, if player is between 50 to 100% then its color is GREEN, if it is less than 50 and equal to 25 its color is ORANGE and under 25% is RED color. I have attached a python code
I would be very thankful if anybody help
def draw_shield_bar(surf, x, y, pct):
I have a progress bar in the code which only shows a GREEN color but i want to modify it with the percentage of a player, if player is between 50 to 100% then its color is GREEN, if it is less than 50 and equal to 25 its color is ORANGE and under 25% is RED color. I have attached a python code
I would be very thankful if anybody help
def draw_shield_bar(surf, x, y, pct):
if pct < 0:
pct = 0
BAR_LENGTH = 100
BAR_HEIGHT = 10
fill = (pct / 100) * BAR_LENGTH
outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)
fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
pygame.draw.rect(surf, GREEN, fill_rect)
pygame.draw.rect(surf, WHITE, outline_rect, 2)
回答1:
Just set the color dependent on the percentage:
color = GREEN if pct >= 50 else ORANGE if pct >= 25 else RED
pygame.draw.rect(surf, color, fill_rect)
By the way, the parameters to pygame.Rect() have to be integral, so when you calculate fill
, then you've to use the integral division operator (//
), rathet then the floating point division (/
):
fill = BAR_LENGTH * pct // 100
来源:https://stackoverflow.com/questions/57033885/how-to-show-shields-level-by-changing-color-of-the-progress-bar