2016-03-21 194 views
1

我是Python新手,開始學習Eric Matthes的「Python速成教程」。我在Pygame章節的開始,我遵循代碼,但我加載的圖像總是看起來損壞,我不知道爲什麼。代碼來自該書。第一個文件:Python Pygame無法正確顯示圖像

import pygame 
    class Ship(): 
     def __init__(self, screen): 
      """Initialize the ship and set its starting position.""" 

    # Load the ship image and get its rect. 
      self.image = pygame.image.load('ship.bmp') 
      self.screen = screen 
      self.rect = self.image.get_rect() 
      self.screen_rect = screen.get_rect() 
    # Start each new ship at the bottom center of the screen. 
      self.rect.centerx = self.screen_rect.centerx 
      self.rect.bottom = self.screen_rect.bottom 
     def blitme(self): 
      self.screen.blit(self.image, self.rect) 

第二個文件:

import sys 
    import pygame 
    from settings import Settings 
    from ship import Ship 
    def run_game(): 
     # Initialize game and create a screen object. 
     pygame.init() 
     ai_settings = Settings() 
     screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) 
     pygame.display.set_caption("Alien Invasion") 
     ship = Ship(screen) 
     bg_color = (230, 230, 230) 

     # Start the main loop for the game. 
     while True: 
      # Watch for keyboard and mouse events. 
      for event in pygame.event.get(): 
       if event.type == pygame.QUIT: 
        sys.exit()  
      # Make the most recently drawn screen visible. 

      screen.fill(ai_settings.bg_color) 
      ship.blitme() 


      pygame.display.flip() 


    run_game() 

設置文件:

class Settings(): 
     """A class to store all settings for Alien Invasion.""" 
     def __init__(self): 
      """Initialize the game's settings.""" 
      # Screen settings 
      self.screen_width = 800 
      self.screen_height = 600 
      self.bg_color = (230, 230, 230) 

我BMP樣子說:

enter image description here

我試圖添加d ifferent圖像,但沒有運氣:

enter image description here

我怎樣才能解決呢?

+0

難道你不需要在你的圖像上應用convert()嗎? – 2016-03-21 17:56:38

+0

我不知道,書代碼中沒有這樣的東西。我該如何修改我的代碼? – migari

+0

'self.image = pygame.image.load( 'ship.bmp')轉換()' - 只是'轉換嘗試()'末 – 2016-03-21 19:00:04

回答

1

我推測你在Mac上,有一個相對較新版本的SDL。問題不在於您的代碼,而是SDL的新版本在Mac OS中存在一個錯誤。

要解決,您可能需要您的SDL的版本降級大約1.2之前的版本(這是圍在那裏,忘了確切的版本),或在不同的操作系統上運行。

這很煩人。我結束了在安裝VirtualBox和我的Mac上運行Linux只是爲了能夠代碼pygame的!

+0

謝謝,我認爲就是這樣,我可以從頭開始嘗試修復代碼。 Mac和El Captain在這裏。 – migari

+0

也El Capitain!讓我知道如果切換到別的東西適合你。這是我的源btw。不幸的是,我沒能降級SDL,所以我不能100%說的這個問題,但它很可能。 http://stackoverflow.com/questions/33582204/images-distorted-using-pygame –