我正在编写一些使用 Pygame 的 Python 代码,试图在背景上显示一个小精灵(一个球)。我有那部分工作,但我试图让球精灵的背景是透明的,所以它不会显示为“黑色正方形内的球”精灵,而是显示黑色像素不是blitted 到显示表面。
这是我的代码:
# For sys.exit()
import sys
# Pygame imports
import pygame
from pygame.locals import *
# Initialize all the Pygame Modules
pygame.init()
# Build a screen (640 x 480, 32-bit color)
screen = pygame.display.set_mode((640,480))
# Create and Convert image files
# Use JPG files for lots of color, and use conver()
# Use PNG files for transparency, and use convert_alpha()
background = pygame.image.load("bg.jpg").convert()
ball = pygame.image.load("ball.png").convert_alpha()
ball.set_colorkey(-1, RLEACCEL) # Use the upper-left pixel color as transparent
# The main loop
while True:
# 1 - Process all input events
for event in pygame.event.get():
# Make sure to exit if the user clicks the X box
if event.type == QUIT:
pygame.quit()
sys.exit()
# 2 - Blit images to screen (main display window)
screen.blit(background, (0,0))
x,y = pygame.mouse.get_pos()
x = x - ball.get_width()/2
y = y - ball.get_height()/2
screen.blit(ball, (x,y))
# 3 - Update the main screen (redraw)
pygame.display.update()
我一定犯了一个明显的错误,但我无法弄清楚。调用 ball.set_colorkey(-1, RLEACCEL) 应该获取球精灵左上角的颜色(恰好是黑色)并将其用作“不 blit”的像素颜色。我错过了一步吗?
谢谢你的帮助。