Oct-26-2023, 10:00 PM
Something like this?
import pygame import sys import math class StatusBar(pygame.sprite.Sprite): def __init__( self, rect=(0, 0, 100, 10), max_=1, min_=0, fg="white", bg="black", center=None, colormap=None, ): super().__init__() self.rect = pygame.Rect(rect) self.bar = pygame.Rect(0, 0, self.rect.width, self.rect.height) self.image = pygame.Surface(self.rect.size) self.colormap = dict(sorted(colormap.items())) if colormap else {} self.fg = fg self.bg = bg self.max = max_ self.min = min_ self.range = self.max - self.min self.center = center self._value = 0 @property def value(self): return self._value @value.setter def value(self, new_value): self._value = max(self.min, min(new_value, self.max)) def update(self): if self.center is None: self.bar.width = int( self.rect.width * (self.value - self.min) / (self.max - self.min) ) else: a = self.rect.width * (self._value - self.min) / self.range b = self.rect.width * (self.center - self.min) / self.range self.bar.x = min(a, b) self.bar.width = abs(a - b) self.image.fill(self.bg) fg = self.fg for value, color in self.colormap.items(): if value <= self._value: fg = color else: break pygame.draw.rect(self.image, fg, self.bar) pygame.init() screen = pygame.display.set_mode((220, 90)) b1 = StatusBar((10, 10, 200, 10), min_=-1) b2 = StatusBar( (10, 30, 200, 10), min_=-1, colormap={-1: "green", 0: "yellow", 0.5: "red"} ) b3 = StatusBar((10, 50, 200, 10), min_=-1, center=0) b4 = StatusBar( (10, 70, 200, 10), min_=-1, center=0, colormap={ -1: "red", -0.75: "orange", -0.5: "yellow", -0.25: "green", 0.25: "yellow", 0.5: "orange", 0.75: "red", }, ) group = pygame.sprite.Group() group.add((b1, b2, b3, b4)) clock = pygame.time.Clock() for i in range(1000): event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit() b1.value = math.sin(math.radians(i)) b2.value = math.cos(math.radians(i)) b3.value = math.sin(math.radians(i)) b4.value = math.cos(math.radians(i)) group.update() group.draw(screen) pygame.display.update() clock.tick(60) pygame.quit()