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