2017-08-14 3 views
1

私はPygameで自分のゲームのライフバークラスを作ろうとしています。私はこれをやった: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() 

答えて

2

を私はあなたのコードは、1つのピクセルよりも長方形少ないを描くので、それはだと思いますpygamedocumentationには「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)) 
+0

高さは10か0ではありませんか? – Foon

+0

@Foon:あなたは間違いなく正解です。更新された回答をご覧ください。 – martineau

+0

ありがとうございます。それは問題を完全に解決します。 – HastatusXXI