我需要做的是将图像背景的颜色与Pygame窗口的颜色进行匹配。 但是图像和pygame窗口的背景不匹配。看起来像这样
ship.py
import pygame
class Ship:
""" A class to manage the ship. """
def __init__(self, ai_game):
""" Initialize the ship and the starting position. """
self.screen = ai_game.screen
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()
# Start each new ship at the bottom center of the screen.
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
""" Draw ship at its current location. """
self.screen.blit(self.image, self.rect)
alieninvasion.py
import sys
import pygame
from ship import Ship
class AlienInvasion:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
# Set background colour
self.bg_color = (0, 0, 255)
self.ship = Ship(self)
def run_game(self):
"""Start the main loop for the game."""
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
self.screen.fill(self.bg_color)
self.ship.blitme()
# Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
I tried the answers from this discussion,但我无法解决。
我不知道如何使用image.convert_alpha()
和image.set_colorkey()
,并且在ship.py中使用它们对我没有任何变化。
注意:ship.py是在船上进行更改的类,而Alieninvasion.py是主文件。
答案 0 :(得分:3)
您无需将图像的背景色更改为窗口的背景色,而是使图像的背景透明。
通过pygame.Surface.set_colorkey
设置透明色键:
设置表面的当前颜色键。将此Surface拖到目标上时,与colorkey颜色相同的任何像素都是透明的。
请注意,所有背景必须具有完全相同的颜色。在您的情况下,背景颜色似乎是灰色的(230、230、230):
self.image = pygame.image.load('images/ship.bmp').convert()
self.image.set_colorkey((230, 230, 230))
另一个选择是创建一个新图像(您需要在绘画应用程序中绘制它),并使用每个像素的alpha(例如PNG)和透明背景:
self.image = pygame.image.load('images/ship.png').convert_alpha()