我想为我在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
覆盖的区域不包括像素的最右边和最下面的边缘”,显然这意味着它总是包括最左边和最上面的边缘,这就是给出结果的原因。这可以被认为是一个bug,在这些情况下它不应该画任何东西下面是一个解决方法,它可以简单地避免绘制小于整个像素宽度的
Rect
。我还简化了正在做的数学,使事情更清楚(更快)相关问题 更多 >
编程相关推荐