Python速成班外星人游戏用background.bmp图像替换背景色

2024-04-18 12:15:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个正在运行的外星人入侵游戏,它来自Python速成教程。但是,我正在应用修改。我试图替换bg_color的值,以表示存储在项目文件夹中的背景图像,而不是颜色,即

self.bg_color = pygame.image.load('images/space.bmp')

当前AlienInvision类从名为settings.py的sep文件中存储的名为settings的类导入背景色


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

AlienInvasion是设置游戏的主要游戏类

class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        """create a settings object using the imported settings class"""
        self.settings = Settings()
        """initialise the game display using the settings saved within the settings file"""
        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        """ assign the imported ship attributes to a new ship instance - "Self" in the call references to a call of AlienInvasion as a class """
        self.ship = Ship(self)
        """ run the game in full screen mode """
        pygame.display.set_caption("Alien Invasion")
        # Set the background color.
        self.bg_color = (230, 230, 230)

更新屏幕随着游戏的进行不断更新屏幕,并在游戏运行时处理背景颜色

def _update_screen(self):
            """Update the images on the screen and flip to the new screen"""  
            # Redraw the screen during each pass through the loop. Use the settings file here
            self.screen.fill(self.settings.bg_color)

我认为我的问题在于.fill()只应用于颜色值(230、230、230)。但我基本上希望屏幕更新为背景图像,而不是静态颜色。有人能帮忙吗?我是否应该使用另一个函数来代替.fill()


Tags: thetoselfgame游戏settingsinit颜色
2条回答

更改Settings中的背景:

class Settings:
    def __init__(self):
        # [...]
    
        self.bg_color = pygame.image.load('images/space.bmp')

AlienInvasion的构造函数中的Settings对象获取背景。如果背景图像的大小与显示不同,我建议使用^{}将背景缩放到正确的大小:

class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        # [...]
        self.settings = Settings()
        # [...]

        self.bg_color = pygame.transform.smoothscale(self.settings.bg_color, 
                            self.screen.get_size())
 

^{}背景而不是^{}显示表面:

class AlienInvasion:
    # [...]

    def _update_screen(self):
        self.screen.blit(self.settings.bg_color, (0, 0))

blit将一个图像绘制到另一个图像上。在这种情况下,它在与显示器相关联的表面上绘制背景图像(表面


请注意,名称bg_color具有误导性。如果您使用的是背景图像,则应将其重命名(例如bg_imagebg_surface

使用:

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

而不是:

self.screen.fill((0, 0, 0))

您的图像应该是屏幕大小,元组是位置

相关问题 更多 >