pythonuser-interfacepygamegauge

Trouble with verticle Pygame status bar


The following code works, but it looks a bit kludgy to me. I wander if there is a better way to write it than my approach. Also its resolution is far too high. If anyone has any ideas as to a better approach and how to slow down the resolution, I would love to hear it. Thank you!

import pygame as pg
from random import randint###RANDOM LIBRARY

pg.init()

screen = pg.display.set_mode((640, 480))
FONT = pg.font.Font(None, 36)
BACKGROUND_COLOR = (37, 225, 192)
BLUE = (0, 0, 199)
GRAY = (0, 0, 55)

#Rectangle variables.
measure_rect = pg.Rect(200, 40, 100, 400)

done = False

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    random_bar=randint(33,34)#Manipulation of bar graph.
    value_print=random_bar
    length = random_bar*4
    random_bar = 100 - random_bar
    top = 40+(random_bar*4)

    screen.fill(BACKGROUND_COLOR)
    pg.draw.rect(screen, BLUE, (200, top, 100, length))
    pg.draw.rect(screen, GRAY, measure_rect, 2)
    txt = FONT.render(str(round(value_print, 2)), True, GRAY)
    screen.blit(txt, (120, 20))

    pg.display.flip()
    
pg.quit()

Solution

  • I recommend to implement a Bar class:

    import pygame as pg
    from random import randint###RANDOM LIBRARY
    
    pg.init()
    
    screen = pg.display.set_mode((640, 480))
    FONT = pg.font.Font(None, 36)
    BACKGROUND_COLOR = (37, 225, 192)
    BLUE = (0, 0, 199)
    GRAY = (0, 0, 55)
    
    class Bar():
        def __init__(self, rect, bar = BLUE, outline = GRAY):
            self.rect = pg.Rect(rect)
            self.bar = bar
            self.outline = outline
            self.value = 0
        def draw(self, surf):
            length = round(self.value * self.rect.height / 100)
            top = self.rect.height - length
            pg.draw.rect(surf, self.bar, (self.rect.x, self.rect.y + top, self.rect.width, length))
            pg.draw.rect(surf, self.outline, self.rect, 2) 
            txt = FONT.render(str(round(self.value, 2)), True, GRAY)
            txt_rect = txt.get_rect(topright = (self.rect.x - 10, self.rect.y))
            screen.blit(txt, txt_rect)   
    
    bar = Bar((200, 40, 100, 400))
    
    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
    
        bar.value = randint(33, 34)
    
        screen.fill(BACKGROUND_COLOR)
        bar.draw(screen)
        pg.display.flip()
        
    pg.quit()