2017-01-04 15 views
1

私はPygameでOOPを学び、簡単なゲームを作ろうとしています。私はゆるやかにチュートリアルに従いますが、自分のニーズに合わせて修正しようとしています。私は黒のウィンドウに白い矩形を描画しようとしていますが、チュートリアルでは黒いウィンドウに青い円が描かれています。矩形に置き換えると機能しません。 私のコードは、2つの異なるファイルをHERESに最初のファイルにsepereatedさ:Pygame OOPで矩形を描く

import pygame 
import LanderHandler 

black = (0, 0, 0) 
white = (255, 255, 255) 
green = (0, 255, 0) 
red = (255, 0, 0) 


class MainLoop(object): 
    def __init__(self, width=640, height=400): 

     pygame.init() 
     pygame.display.set_caption("Lander Game") 
     self.width = width 
     self.height = height 
     self.screen = pygame.display.set_mode((self.width, self.height), pygame.DOUBLEBUF) 
     self.background = pygame.Surface(self.screen.get_size()).convert() 

    def paint(self): 
     lander = LanderHandler.Lander() 
     lander.blit(self.background) 

    def run(self): 

     self.paint() 
     running = True 

     while running: 

      for event in pygame.event.get(): 
       if event.type == pygame.QUIT: 
        running = False 
       elif event.type == pygame.KEYDOWN: 
        if event.key == pygame.K_ESCAPE: 
         running = False 

      pygame.display.flip() 

     pygame.quit() 


if __name__ == '__main__': 
    # call with width of window and fps 
    MainLoop().run() 

そして、私の第二のファイル:

import pygame 

black = (0, 0, 0) 
white = (255, 255, 255) 
green = (0, 255, 0) 
red = (255, 0, 0) 


class Lander(object): 
    def __init__(self, height=10, width=10, color=white, x=320, y=240): 
     self.x = x 
     self.y = y 
     self.height = height 
     self.width = width 
     self.surface = pygame.Surface((2 * self.height, 2 * self.width)) 
     self.color = color 

     pygame.draw.rect(self.surface, white, (self.height, self.height, self.width, self.width)) 

    def blit(self, background): 
     """blit the Ball on the background""" 
     background.blit(self.surface, (self.x, self.y)) 

    def move(self, change_x, change_y): 
     self.change_x = change_x 
     self.change_y = change_y 

     self.x += self.change_x 
     self.y += self.change_y 

     if self.x > 300 or self.x < 0: 
      self.change_x = -self.change_x 
     if self.y > 300 or self.y < 0: 
      self.change_y = -self.change_y 

任意のヘルプまたは右方向に私を指していることは素晴らしいだろうありがとうございました。 P.P.実行エラーはなく、黒いウィンドウがポップアップしますが、白い矩形はありません。

+0

self.backgroundをブリットする必要があります:'コードの主要な部分があると、あなたは、このループには何も描画しませんあなたは画面上に何も持っていません。 – furas

答えて

0

blitという名前の関数を作成しないでください。実際のblit関数の途中で機能する可能性があるためです。また、右ここに第二のコードで:

pygame.draw.rect(self.surface, white, (self.height, self.height, self.width, self.width)) 

あなたがself.background

lander.blit(self.background) 

表面に四角形を描画ができますが、メインのバッファであるself.screenself.backgroundをブリットないため

+0

私は従っていない...表面を使用して、どういう意味ですか? –

2

問題がある表面を使用する必要がありますあなたが行うときにモニタに送信されます

pygame.display.flip() 

だから、self.screen

lander.blit(self.screen) 

に直接描画することができます。また、実行中の `ながらself.screen

lander.blit(self.background) 

self.screen.blit(self.background, (0,0))