I am fairly new to programming, so I bought the Book “Python Crash Course” by Eric Matthes. Recently, I decided to recreate the Pokemon Battle System in Pygame. So far, I have made a good enough framework to start the battle system. I picked the Pokemon Mew as a test subject. I already have the transparent backround for the picture, but pygame still shows the gray and white squares. This is my main code-file:
from settings import Settings
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Pykemon Battle Simulator")
pokemon = Mew(screen)
mixer.music.load("battle_music.mp3")
mixer.music.play(-1)
while True:
screen.fill(ai_settings.bg_color)
pokemon.blitme()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
run_game()
And this is my settings file for Mew:
import pygame
class Mew():
def __init__(self, screen):
"""Initialize the Pokémon Mew and it's location """
self.screen = screen
#Load the pokemon and get it's rect.
self.image = image = pygame.image.load("mew.jpg").convert_alpha()
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#Start each new Pokemon at the bottom of the screen
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
def blitme(self):
"""Draw the pokemon's current location"""
self.screen.blit(self.image, self.rect)
And this(https://imgur.com/a/OytJBUN) is how it turned out. How can I make the of the Picture backround transparent?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The issue is the image format. JPEG images have no alpha channel. You can set a transparent colorkey by set_colorkey(), but the result will not satisfy you, because the JPEG is not lossless. That means due the compression, the colors will slightly change and the color key will not work correctly. For instance white color:
self.image = image = pygame.image.load("mew.jpg")
self.image.set_colorkey((255, 255, 255))
Either use set_colorkey() and a lossless image format like BMP:
self.image = image = pygame.image.load("mew.bmp")
self.image.set_colorkey((255, 255, 255))
or us the PNG format. For instance:
image = pygame.image.load("mew.png").convert_alpha()
Method 2
Use a PNG with the convert_alpha() function:
image = pygame.image.load("image.png").convert_alpha()
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0