Pygame:绘制矩形的奇怪行为
问题描述:
我想在Pygame中为我的游戏制作一个lifebar类。我已经做到了这一点: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个像素尽管pygame
documentation表示“Rect
覆盖的区域不包括像素的右侧和最底部边缘”,但显然这意味着它始终包含左侧和最顶部的边缘确实包括左侧和顶部边缘,这是什么给结果。这可以说是一个错误 - 在这种情况下它不应该画任何东西。
下面是一个解决方法,它简单地避免了绘制Rect
s,它们的宽度小于整个像素。我还简化了正在做的一些数学工作,使事情更加清晰(和更快)。
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
@Foon:你绝对正确,我的错误。查看更新的答案。 – martineau
谢谢。它完全解决了这个问题。 – HastatusXXI