I'm trying to make a health bar that scales the colors of GREEN to RED depending on the percentage of health. Basically, i'm trying to make the value of 0.5 correspond to (255, 255, 0), and a value of 1.0 correspond to (0, 255, 0) and a value of 0.0 correspond to (255,0,0). I saw This Post, which has the same intent as I, but doesn't quite help code-wise. Same applies f?r This Post.
This is my current code:
def draw_player_health_mana(surface, x, y, curr_value, start_value, type_bar, font):
#TRANSFORMS THE VALUES TO PERCENTAGE
pct = curr_value/start_value
if pct < 0:
pct = 0
#SIZE OF THE HEALTH BAR
BAR_LENGTH = 150
BAR_HEIGHT = 18
#INITIAL COLOR VALUES
red_color = 255
green_color = 255
#THE FILLED BAR TO DISPLAY VISUALLY OF CURRENT HP COMPARED TO MAX HP
fill = pct * BAR_LENGTH
#PYGAME RECTANGLES
outline_rect = pg.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)
fill_rect = pg.Rect(x, y, fill, BAR_HEIGHT)
#CHECKS WHAT TYPE OF BAR IS CALLED FOR - THERES MANA AND HEALTH
if type_bar == 'health':
#THE DIFFERENCE IN PERCENTAGE, MEANT AS AN INCREASE
pct_diff = 1.0 - pct
#INTENT IS TO CHECK IF PERCENTAGE IS ABOVE 50%, THEN DECREASE THE GREEN SPECTRUM
#BUT AS SHOWN, IT NEVER DECREASES TO 0, BUT ONLY TO HALF OF 255...
#LIKEWISE FOR THE INCREASE OF RED_COLOR
if pct > 0.5:
red_color = 255 * pct #### Can't really figure out how to deal with this part
else:
green_color = 255*pct_diff
col = (red_color, green_color, 0)
print(col)
elif type_bar == 'mana':
col = BLUE
pg.draw.rect(surface, col, fill_rect)
pg.draw.rect(surface, BLACK, outline_rect, 2)
text = font.render(str(curr_value) + "/" + str(start_value), True, BLACK)
text_rect = text.get_rect(center=(BAR_LENGTH/2 + x, BAR_HEIGHT/2 + y))
surface.blit(text, text_rect)
As commented in the syntax above, the issue is the color conversion. Color works as (RED, GREEN, BLUE). For a nice green color of having full health, it should be (0, 255, 0). However, as the health shifts towards 50%, the red color must reach the value of 255 (Causing for (255, 255, 0), which i cannot figure out how to effectively do whilst transitioning the decrease in green to 0 to reach a more of a red color.. I feel really lost on this matter, and any type of help would be greatly appreciated.
Thanks in advance.
question from:
https://stackoverflow.com/questions/65904437/shifting-the-color-value-based-on-percentage-from-green-to-red-using-pygame