【问题标题】:Shifting the color value based on percentage from green to red using PyGame使用 PyGame 将基于百分比的颜色值从绿色变为红色
【发布时间】:2021-04-30 10:03:57
【问题描述】:

我正在尝试制作一个根据健康百分比将绿色颜色缩放为红色的健康栏。基本上,我试图使0.5的值对应于(255,255,0),1.0的值对应于(0,255,0),0.0的值对应于(255,0,0) .我看到了This Post,它的意图与我相同,但在代码方面并没有多大帮助。同样适用于This Post

这是我当前的代码:

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)

如上面语法中所述,问题在于颜色转换。颜色为(红色、绿色、蓝色)。对于具有完整健康的漂亮绿色,它应该是 (0, 255, 0)。然而,随着生命值向 50% 转变,红色必须达到 255 的值(导致 (255, 255, 0),我无法弄清楚如何有效地做到这一点,同时将绿色的减少转换为 0 以达到更多的是红色。我在这件事上感到非常迷茫,任何类型的帮助都将不胜感激。

提前致谢。

【问题讨论】:

    标签: python colors pygame


    【解决方案1】:

    0.5对应(255,255,0),1.0对应(0,255,0)(255,255,0),1.0对应(0,255,0)

    因此绿色分量为min(255, pct_diff*2 * 255),红色分量为min(255, pct*2 * 255)

    pct_diff = 1.0 - pct
    red_color = min(255, pct_diff*2 * 255)
    green_color = min(255, pct*2 * 255)
    col = (red_color, green_color, 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 2020-09-19
      • 2021-07-07
      • 1970-01-01
      • 2021-06-15
      • 2017-05-28
      相关资源
      最近更新 更多