[英]Pygame: strange behaviour of a drawn rectangle
我正在尝试为我在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
文档说“ Rect
所覆盖的区域不包括像素的最右端和最底端”,这显然意味着它始终会包括最左边和最上面的边缘,这就是结果。 可以将其视为错误,并且在那种情况下不应画任何东西。
以下是一种解决方法,可以避免绘制小于整个像素宽的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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.