Pygame:绘制矩形的奇怪行为

时间:2017-08-14 18:43:48

标签: 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):
        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)

它有效,但当我尝试将其生命值降低到零时,矩形超过左边界限一点。为什么会这样?

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

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()  

1 个答案:

答案 0 :(得分:2)

我认为这是因为您的代码会绘制小于1像素宽的矩形,即使pygame documentation表示" Rect涵盖的区域不包括像素的右边和最底边#34;显然这意味着它总是 包括左边和最顶边,这就是给出结果的东西。这可以说是一个错误 - 它不应该在这些情况下得出任何东西。

下面是一种解决方法,可以简单地避免绘制小于整个像素宽度的Rect。我还简化了数学操作,使事情更清晰(更快)。

    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))