gpt4 book ai didi

python - 如何转换图像的背景颜色以匹配 Pygame 窗口的颜色?

转载 作者:行者123 更新时间:2023-12-05 06:48:14 24 4
gpt4 key购买 nike

我需要做的是将图像背景的颜色与 Pygame 窗口的颜色相匹配。但是图片背景和pygame窗口不匹配。看起来像这样

船.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)

外星人入侵

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 是主文件。

最佳答案

不需要将图片的背景色改为窗口的背景色,而是将图片的背景设为透明。


通过pygame.Surface.set_colorkey设置透明色键:

Set the current color key for the Surface. When blitting this Surface onto a destination, any pixels that have the same color as the colorkey will be transparent.

请注意,所有背景的颜色必须完全相同。在您的情况下,背景颜色似乎是灰色(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()

关于python - 如何转换图像的背景颜色以匹配 Pygame 窗口的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66865608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com