2017-01-04 51 views
1

我想用pygame學習OOP並做一個簡單的遊戲,我鬆散地遵循一個教程,但試圖修改它以適合我自己的需求,現在它不工作。我試圖在黑色的窗口上繪製一個白色的矩形,教程在黑色的窗口上繪製一個藍色圓圈,當我將圓圈替換爲矩形時,它不起作用。 我的代碼是sepereated到2個不同的文件繼承人的第一個文件: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.S.我沒有運行錯誤,並且彈出一個黑色的窗口,但沒有白色的矩形。

+0

的blit self.background運行'而:'是的代碼主要部分和你沒有這個循環畫什麼所以你在屏幕上沒有任何東西。 – furas

回答

0

您不應該創建一個名稱爲blit的函數,因爲它可能妨礙實際的blit函數。此外這裏在第二代碼:

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

你應該使用表面

+0

我不遵循...你是什麼意思,通過使用表面? –

2

問題是因爲你繪製矩形上表面self.background

lander.blit(self.background) 

但你永遠不上self.screen的blit self.background這是主緩衝區並在顯示器上發送時發送

pygame.display.flip() 

所以,你可以在self.screen

lander.blit(self.screen) 

直接繪製或您必須對self.screen

lander.blit(self.background) 

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