首页 > 解决方案 > 在 pygame 空间入侵者的按键上交换船舶图像

问题描述

我想在使用 pygame 的太空侵略者游戏中拥有替代角色。如果我按 1,我希望游戏将船舶切换到船舶 1,如果我按 2,我希望游戏切换到船舶 2,依此类推。

我曾尝试在我的 ship.py 文件中更改 self.image,以便:

    for event in pygame.event.get():
         if event.type == pygame.K_1:
              self.image = pygame.image.load('images/ship1.bmp')
              self.image.get_rect()
         elif event.type == pygame.K_2:
              self.image == pygame.image.load('images/ship2.bmp')
              self.image.get_rect()

但这会在我的主要外星人入侵程序中返回一些关于船级的错误。

下面是我加载的静态图像的工作代码,这也是我尝试使用 if 和 elif 语句更改的代码。任何建议将不胜感激。如果它有帮助,我是一个非常笨拙的编码器。

class Ship(Sprite):
    """A class to manage the ship."""
 
    def __init__(self, ai_game):
        """Initialize the ship and set its starting position."""
        super().__init__()
        self.screen = ai_game.screen
        self.settings = ai_game.settings
        self.screen_rect = ai_game.screen.get_rect()

        # Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()

标签: pythonimagepygame

解决方案


首先加载不在循环中的图像。

image1 = pygame.image.load('image1')
image2 = pygame.image.load('image2')
 #replace image 1 with your image
 #in the event loop
 screen.blit(image1, (Your wish dimensions))
 #note that I took screen.blit because I made my screen in a variable called screen.
 #If you variable is display take display.blit
 if event.type == pygame.KEYDOWN:
    if pygame.key == pygame.K_RIGHT:
       image1 = image 2

推荐阅读