我需要制作一个类来绘制字符
屏幕中心,并使图像的背景颜色与屏幕的背景颜色匹配,反之亦然。我已经将Pygame屏幕的背景色的值设置为蓝色,但是当我在DrawCharacter
类中执行同样的操作时,它只是使用图像的背景色(白色)打开了屏幕。我可能只是将bg_color
属性放在班级的错误位置。
game_character.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文件
答案 0 :(得分:0)
如果图像具有透明背景,请尝试在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()