Python 绘制背景图片时,背景图片覆盖精灵的问题

167 阅读2分钟

在使用 Python Pygame 开发游戏中,用户遇到了一个问题。当他们将背景图片添加到游戏中时,背景图片会覆盖精灵,导致精灵无法正常显示。

huake_00198_.jpg 2. 解决方案

为了解决这个问题,我们需要将背景图片添加到一个单独的精灵组中,然后在绘制时只绘制这个精灵组,这样就可以避免背景图片覆盖精灵的问题。

# 创建一个背景精灵组
background_group = pygame.sprite.Group()

# 将背景图片添加到背景精灵组
background = pygame.image.load("background.png")
background_group.add(background)

# 在绘制时只绘制背景精灵组
background_group.draw(screen)

通过这种方法,背景图片就不会再覆盖精灵了。

# Initialize Pygame
pygame.init()

# Set the height and width of the screen
screen_width=700
screen_height=600
screen=pygame.display.set_mode([screen_width,screen_height])
pygame.display.set_caption('Razazone')

clock.tick(70)

#This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()

# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

# 创建一个背景精灵组
background_group = pygame.sprite.Group()

# This represents a background
background = Background(20,15)

# Set a location for the block
background.rect.x = (screen_width)
background.rect.y = (screen_height)

# 将背景图片添加到背景精灵组
background_group.add(background)

# Add the block to the list of objects
# all_sprites_list.add(background)

for i in range(1):
    # This represents a block
    block = Block(black, 20, 15)

    # Set a random location for the block
    block.rect.x = random.randrange(screen_width)
    block.rect.y = random.randrange(screen_height)

    # Add the block to the list of objects
    block_list.add(block)
    all_sprites_list.add(block)

    # Create a red player block
    player = Player(350, 300)
    all_sprites_list.add(player)


done=False

# -------- Main Program Loop -----------
while done==False:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop# 

    # Calls update() method on every sprite in the list
    all_sprites_list.update()

    # See if the player block has collided with anything.
    blocks_hit_list = pygame.sprite.spritecollide(player, block_list, False)  

    # Check the list of collisions.
    for block in blocks_hit_list:
        lives -=1
        print (lives)
        # Reset block to the top of the screen to fall again.
        block.reset_pos()


    # Reset block to the right of the screen to fall again.
    #background.reset_pos()

    if lives<=1:
        lives=1

    screen.fill(black)
    #background.update()

    # 在绘制时只绘制背景精灵组
    background_group.draw(screen)

    # Draw all the spites
    all_sprites_list.draw(screen)

    lives_text=font.render("%d lives" % lives, True, white)
    screen.blit(lives_text, [100,100])


    #background.update()

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

pygame.quit()