2016-03-21 166 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 –