由于整个精灵“颜色”都被粉红色填充,解决这个问题的一个巧妙方法是使精灵主色透明,然后将其覆盖到所需色调的相同大小的矩形上。
先制作一条透明背景的鱼(我用TheGIMP编辑)。
clear_fish.png
然后在你的精灵类中(或者你想实现它),创建一个相同大小的pygame.Surface,用所需的颜色填充它。然后blit() 彩色表面上的透明鱼图像。
fish_image = pygame.image.load( 'clear_fish.png' ) # un-coloured fish
fish_rect = fish_image.get_rect()
# Apply some coloured scales to the fish
fish_scales= pygame.Surface( ( fish_rect.width, fish_rect.height ) )
fish_scales.fill( colour )
fish_scales.blit( fish_image, (0,0) )
fish_image = fish_scales # use the coloured fish
参考:完整示例代码~
import pygame
import random
# Window size
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
WINDOW_SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE
DARK_BLUE = ( 3, 5, 54)
### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption("1-Fish, 2-Fish, Pink Fish, Clear Fish")
class FishSprite( pygame.sprite.Sprite ):
def __init__( self, colour ):
pygame.sprite.Sprite.__init__( self )
self.image = pygame.image.load( 'clear_fish.png' )
self.rect = self.image.get_rect()
# Apply some coloured scales to the fish
fish_scales= pygame.Surface( ( self.rect.width, self.rect.height ) )
fish_scales.fill( colour )
fish_scales.blit( self.image, (0,0) )
self.image = fish_scales # use the coloured fish
# Start position is randomly across the screen
self.rect.center = ( random.randint(0, WINDOW_WIDTH), random.randint(0,WINDOW_HEIGHT) )
def update(self):
# Just move a bit
self.rect.x += random.randrange( -1, 2 )
self.rect.y += random.randrange( -1, 2 )
### Sprites
fish_sprites = pygame.sprite.Group()
fish_sprites.add( FishSprite( ( 255, 200, 20 ) ) ) # add some fish
fish_sprites.add( FishSprite( ( 255, 20, 200 ) ) )
fish_sprites.add( FishSprite( ( 55, 00, 200 ) ) )
fish_sprites.add( FishSprite( ( 20, 200, 20 ) ) )
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.MOUSEBUTTONUP ):
# On mouse-click add a fish
mouse_pos = pygame.mouse.get_pos()
random_red = random.randint( 50, 250 )
random_green = random.randint( 50, 250 )
random_blue = random.randint( 50, 250 )
random_colour = ( random_red, random_green, random_blue )
fish_sprites.add( FishSprite( random_colour ) )
# Update the window, but not more than 60fps
fish_sprites.update()
window.fill( DARK_BLUE )
fish_sprites.draw( window )
pygame.display.flip()
# Clamp FPS
clock.tick_busy_loop(60)
pygame.quit()