python - Pygame: strange behaviour of a drawn rectangle -


i'm trying make lifebar class game in pygame. i've done this:

class lifebar():     def __init__(self, x, y, max_health):         self.x = x         self.y = y         self.health = max_health         self.max_health = max_health      def update(self, surface, add_health):         if self.health > 0:             self.health += add_health             pygame.draw.rect(surface, (0, 255, 0), (self.x, self.y, 30 - 30 * (self.max_health - self.health) / self.max_health, 10))       print(30 - 30 * (self.max_health - self.health) / self.max_health) 

it works, when tried down health zero, rectangle surpasses left limit bit. why happen?

here have code try on own (just run if explanation of problem wasn't clear):

import pygame pygame.locals import * import sys  width = 640 height = 480  class lifebar():     def __init__(self, x, y, max_health):         self.x = x         self.y = y         self.health = max_health         self.max_health = max_health      def update(self, surface, add_health):         if self.health > 0:             self.health += add_health             pygame.draw.rect(surface, (0, 255, 0), (self.x, self.y, 30 - 30 * (self.max_health - self.health) / self.max_health, 10))         print(30 - 30 * (self.max_health - self.health) / self.max_health)  def main():     pygame.init()      screen = pygame.display.set_mode((width, height))     pygame.display.set_caption("prueba")       clock = pygame.time.clock()      lifebar = lifebar(width // 2, height // 2, 100)      while true:         clock.tick(15)         event in pygame.event.get():             if event.type == pygame.quit:                 sys.exit()          screen.fill((0,0,255))          lifebar.update(screen, -1)          pygame.display.flip()  if __name__ == "__main__":     main()   

i think it's because code draws rectangles less 1 pixel wide, , though pygame documentation says "the area covered rect not include right- , bottom-most edge of pixels", apparently implies does include left- , top-most edges, giving results. arguably considered bug—and shouldn't draw in cases.

below workaround avoids drawing rects less whole pixel wide. simplified math being done bit make things more clear (and faster).

    def update(self, surface, add_health):         if self.health > 0:             self.health += add_health             width = 30 * self.health/self.max_health             if width >= 1.0:                 pygame.draw.rect(surface, (0, 255, 0),                                   (self.x, self.y, width, 10))                 print(self.health, (self.x, self.y, width, 10)) 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -