【问题标题】:Pygame: strange behaviour of a drawn rectanglePygame:绘制矩形的奇怪行为
【发布时间】:2017-08-14 18:43:48
【问题描述】:

我正在尝试在 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()  

【问题讨论】:

    标签: python pygame sprite draw rectangles


    【解决方案1】:

    我认为这是因为您的代码绘制了小于 1 像素宽的矩形,即使 pygame documentation 表示“Rect 覆盖的区域不包括像素的最右边和最底部边缘",显然这意味着它总是确实包括最左边和最上面的边缘,这就是给出结果的原因。这可以说是一个错误——在这种情况下它不应该绘制任何东西。

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

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

    【讨论】:

    • 高度不是10还是0吗?
    • @Foon:你是绝对正确的,我的错。查看更新的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多