1
我想在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()
是不是10或0的高度? – Foon
@Foon:你绝对正确,我的错误。查看更新的答案。 – martineau
谢谢。它完全解决了这个问题。 – HastatusXXI