如何用alpha清除Sprite表动画的旧图像

时间:2017-06-21 00:22:42

标签: python pygame

我是pygame开发的初学者,当我更新我的spritesheet图片时,旧图像仍然存在于表面。

如何清除表面?

image

  

main.py

FPS = 10

try:
    import sys
    import random
    import math
    import os
    import getopt
    import pygame
    from socket import *
    from pygame.locals import *
    from player import *
except ImportError as err:
    print("Couldn't load module. {}".format( err ) ) 
    sys.exit(2)

pygame.init()
fps_clock = pygame.time.Clock()

screen = pygame.display.set_mode((600, 600))

game_surface = pygame.Surface(screen.get_size())
game_surface.fill((250,250,250))
game_surface_image = pygame.image.load("data/landscape.jpg").convert()
game_surface.convert()

p = Player()
player_surface = pygame.Surface((p.SPRITE_WIDTH, p.SPRITE_HEIGHT), pygame.SRCALPHA)

# ---------------------------------------------------------------
# MAIN LOOP -----------------------------------------------------
# ---------------------------------------------------------------

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    screen.fill((250,250,250))

    pygame.display.set_caption("FPS: {:.2f}".format(fps_clock.get_fps()))

    p.animation()

    player_surface.blit(p.image, (0,0), p.rect)
    game_surface.blit(game_surface_image, (0,0))
    game_surface.blit(player_surface, (screen.get_rect().centerx - p.SPRITE_WIDTH/2, screen.get_rect().centery - p.SPRITE_HEIGHT/2))
    screen.blit(game_surface, (0,0))
    pygame.display.update()


    fps_clock.tick(FPS)
  

player.py

import pygame
from pygame.locals import *

class Player(pygame.sprite.Sprite):

    SPRITE_HEIGHT = 110
    SPRITE_WIDTH = 60
    SPRITE_QTY = 8
    SPRITE_NAME = "data/player_sprite.png"

    __ANIMATION_INTERVAL = 12
    __ANIMATION_COUNT = 0
    __SPRITE_POSITION = 0

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(self.SPRITE_NAME).convert_alpha()
        self.rect = (0, 0, self.SPRITE_WIDTH, self.SPRITE_HEIGHT)

    def animation(self):
        if self.__ANIMATION_COUNT == self.__ANIMATION_INTERVAL:
            self.__ANIMATION_COUNT = 0
            if self.__SPRITE_POSITION < self.SPRITE_QTY - 1:
                self.__SPRITE_POSITION += 1
            else:
                self.__SPRITE_POSITION = 0
            self.rect = Rect(self.SPRITE_WIDTH * self.__SPRITE_POSITION, 0, self.SPRITE_WIDTH  * self.__SPRITE_POSITION + self.SPRITE_WIDTH, self.SPRITE_HEIGHT)
        else:
            self.__ANIMATION_COUNT += 1

1 个答案:

答案 0 :(得分:0)

问题出在这一行: player_surface.blit(p.image, (0,0), p.rect)

播放器图像再次位于旧图像的顶部。需要首先清除player_surface

使用player_surface.fill(BLANK_ALPHA)添加BLANK_ALHPA = (0, 0, 0, 0)应该可以解决问题。

player_surface.fill(BLANK_ALPHA)
player_surface.blit(p.image, (0,0), p.rect)