Python Pygame:绘制矩形的奇怪行为

Python Pygame:绘制矩形的奇怪行为,python,pygame,sprite,draw,rectangles,Python,Pygame,Sprite,Draw,Rectangles,我想在Pygame中为我的游戏制作一个救生艇类。我已经做到了: 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):

我想在Pygame中为我的游戏制作一个救生艇类。我已经做到了:

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)
它可以工作,但当我尝试将其健康度降为零时,矩形超出了左侧限制一点。为什么会发生这种情况

这里有一个代码,您可以自己尝试(如果我对问题的解释不清楚,请运行它):


我认为这是因为您的代码绘制的矩形宽度小于1像素,即使
pygame
说“矩形所覆盖的区域不包括像素的最右边和最下面的边缘”,显然这意味着它总是包括最左边和最上面的边缘,这就是给出结果的地方。这可以被认为是一个bug,在这些情况下它不应该画任何东西

下面是一个解决方法,它可以简单地避免绘制小于整个像素宽度的
Rect
s。我还简化了正在做的数学运算,使事情更清楚(更快)


那不是10或0的高度吗?@Foon:你完全正确,我错了。请参阅更新的答案。
import pygame
from 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)
        for 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()  
    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))