python - 如何将图像的背景颜色与 Pygame 的背景颜色匹配?
问题描述
我需要制作一个在屏幕中心绘制角色并将图像的背景颜色与屏幕背景颜色匹配的类,反之亦然。我已经将 Pygame 屏幕的背景颜色值设置为蓝色,但是当我在DrawCharacter
课堂上执行相同操作时,它只会以图像的背景颜色(白色)打开屏幕。我可能只是将bg_color
属性放在课堂上的错误位置。
游戏角色.py
import sys
import pygame
class DrawCharacter():
bg_color = ((0, 0, 255))
def __init__(self, screen):
"""Initialize the superman and set starting position"""
self.screen = screen
# Load image and get rect
self.image = pygame.image.load("Images/supermen.bmp")
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
# Start each new supermen at the center of the screen
self.rect.centerx = self.screen_rect.centerx
self.rect.centery = self.screen_rect.centery
def blitme(self):
"""Draw the superman at its current location"""
self.screen.blit(self.image, self.rect)
blue_sky.py
import sys
import pygame
from game_character import DrawCharacter
def run_game():
# Initialize game and make screen object
pygame.init()
screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Blue Sky")
bg_color = (0, 0, 255)
# Make superman
superman = DrawCharacter(screen)
# Start the main loop for the game
while True:
# Check for keyboard and mouse events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw screen during each loop pass
screen.fill(bg_color)
superman.blitme()
# make the most recently drawn screen visible
pygame.display.flip()
run_game()
我希望图像的背景颜色与 Pygame 屏幕的背景颜色相同,但事实并非如此。第一个代码块是我的类文件,而第二个是 pygame 文件
解决方案
如果图像具有透明背景,请尝试在 game_Character.py 中执行以下操作:
# Load image and get rect
self.image = pygame.image.load("Images/supermen.bmp").convert_alpha()
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
如果它具有白色背景,您可能希望像这样设置颜色键:
# Load image and get rect
self.image = pygame.image.load("Images/supermen.bmp").convert()
self.image.set_colorkey((255, 255, 255))
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
推荐阅读
- php - VSCode 通过删除该行的其余部分进行搜索和替换
- facebook - 通过个人网站 c# 在 facebook 主墙或时间轴上发帖需要哪些权限?
- git - Git:如何将一个文件从分支 A 的更改应用到同一 repo 的分支 B 中的另一个文件?
- vue.js - Font Awesome 5 图标在 Nuxt 的 Vuetify 中不起作用
- javascript - 未找到导出错误 - 更新到 angular-10 后
- angular - 使用异步管道时的 ExpressionChangedAfterItHasBeenCheckedError
- javascript - 如何在javascript中使用url更新重新加载窗口
- scala - java.lang.ClassCastException:java.lang.String 无法转换为 java.lang.Float
- windows - 无法打开 Visual Studio 代码
- llvm - `ConstantInt::getTrue (LLVMContext &Context)` 和 `ConstantInt::getTrue (Type *Ty)` 有什么区别?