Transparent background not disappearing when displayed on pygame window - python

I am creating a car game and have come across a problem. I've added a car image with a transparent background into my code but the car appears on the screen with the transparent background visible. I want to make the background to disappear. This is a link to the image: https://www.pngfind.com/mpng/bboJib_car-top-view-png-audi-transparent-png/
Here is the code:
import pygame
pygame.init()
import pygame
pygame.init()
black = (0, 0, 0)
#screen
screen_width = 600
screen_length = 800
screen = pygame.display.set_mode((screen_length, screen_width))
clock = pygame.time.Clock()
FPS = 60
#the car i am having trouble with
car2Img = pygame.image.load('car2.png')
car2_X = 0
car2_Y = 0
carX_change = 0
def car2(x, y):
screen.blit(car2Img, (x, y))
running = True
while running:
screen.fill((119, 118, 110))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
car2(car2_X, car2_Y)
clock.tick(FPS)
pygame.display.update()
pygame.quit()

In order to remove the background from a png image you must use the convert_alpha() function when loading it:
car2Img = pygame.image.load('car2.png').convert_alpha()
If your image doesn't contain alpha then you can use a color key to remove the background:
car2Img.set_colorkey(colorOfBackground)

Related

Python, pygame.image.load() function problem

I followed a turtorial where I was lerning to create games using pygame. I just started and I already have a problem. It says it has trouble with finding the image. Here is what it says:
C:\Users\Patryk\AppData\Local\Programs\Python\Python39\python.exe:
can't open file ''
C:\Users\Patryk\PycharmProjects\PePeSza-Game\main.py: [Errno 2]
I tried looking for someone with same problem, but couldn't find the anwser to my question. Here is whole code:
import pygame
pygame.init()
# Game window
screen_width = 800
screen_height = 640
lower_margin = 100
side_margin = 300
screen = pygame.display.set_mode((screen_width,screen_height))
screen = pygame.display.set_caption(('Level editor'))
# Importing images
bg_img = pygame.image.load('./bg.png')
# Create function for drawing background
def draw_bg():
screen.blit('bg_img', (0, 0))
# Mainloop
run = True
while run:
draw_bg()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
There are two thing you need to do in the code
removing the ./ before image name. It might be causing issues
# Importing images
bg_img = pygame.image.load('bg.png') # removing the ./
In screen.blit in draw_bg, you were passing string but you need to pass the object made with pygame.image.load
# Create function for drawing background
def draw_bg():
screen.blit(bg_img, (0, 0)) # removing the apostrophe
Full code:
import pygame
pygame.init()
# Game window
screen_width = 800
screen_height = 640
lower_margin = 100
side_margin = 300
screen = pygame.display.set_mode((screen_width,screen_height))
screen = pygame.display.set_caption(('Level editor'))
# Importing images
bg_img = pygame.image.load('bg.png')
# Create function for drawing background
def draw_bg():
screen.blit(bg_img, (0, 0))
# Mainloop
run = True
while run:
draw_bg()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()

sprite image does not appear in pygame

i being following this pygame tutorial and I can't have my sprite show on the window. When I run the program I see the rectangle move on the screen but it just shows all black. I try changing the background color on my rectangle according to the window but i still get nothing. I do notice that the rectangle changes shape according to the different images i try to load. Here is the code. Thank you
import pygame
import random
import os
WIDTH = 800
HEIGHT = 600
FPS = 30
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
#SET ASSETS FOLDERS
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
class Player(pygame.sprite.Sprite):
# sprite for the Player
def __init__(self):
# this line is required to properly create the sprite
pygame.sprite.Sprite.__init__(self)
# create a plain rectangle for the sprite image
self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert()
# find the rectangle that encloses the image
self.rect = self.image.get_rect()
# center the sprite on the screen
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
# any code here will happen every time the game loop updates
self.rect.x += 5
if self.rect.left > WIDTH:
self.rect.right = 0
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Sprite Example")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(GREEN)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
enter code herepygame.display.flip()
pygame.quit()
I just changed one line near the end of the code in your question and it started working:
.
.
.
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(GREEN)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip() # <----- FIX THIS LINE
pygame.quit()

A Python Programming Road Block Type Error: 'pygame.Surface' object is not callable How to Fix

import pygame
pygame.init()
#colors
black = (0,0,0)
white = (255,255,255)
#Screen Display
Width = 1000
Height = 500
gameDisplay = pygame.display.set_mode((Width, Height))
pygame.display.set_caption('Trock')
clock = pygame.time.Clock()
S_1= pygame.image.load('S1.png')
def car(x,y):
gameDisplay.blit(S_1,(x,y))
x = (Width * 0)
y = (Height * 0.3)
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
gameDisplay.fill(white)
S_1(x,y)
pygame.display.update()
clock.tick (60)
pygame.quit()
quit()
I am Trying to load and image onto the display screen (image is called S1 and variable is S_1) but it wont show and says
Pygame.Surface object is not callable.
Any assistance will be greatly appreciated
S_1 is a Surface object. Use blit to draw an image. Actually blit draws one Surface onto another. Hence you need to blit the image onto the Surface associated to the display.
gameDisplay = pygame.display.set_mode((Width, Height))
# [...]
S_1 = pygame.image.load('S1.png')
# [...]
while not crashed:
# [...]
gameDisplay.fill(white)
gameDisplay.blit(S_1, (x, y))
pygame.display.update()
# [...]
See also How to Display Sprites in Pygame?

Pygame blit image with mouse event

I use Pygame in this code. This is like a game that when user hit mouse button, from the mouse position comes a laser image that will go up, and eventually go out of the screen. I am trying to blit an image when the user hit mouse button. This code I am using does not work and I do not know why. My problem starts at the main for loop
import pygame
# Initialize Pygame
pygame.init()
#___GLOBAL CONSTANTS___
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Set the height and width of the screen
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])
#Load Laser image of spaceship
laser_image = pygame.image.load('laserRed16.png').convert()
#Load sound music
sound = pygame.mixer.Sound('laser5.ogg')
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Get the current mouse position. This returns the position
# as a list of two numbers.
sound.play()
#Get the mouse position
mouse_position = pygame.mouse.get_pos()
mouse_x = mouse_position[0]
mouse_y = mouse_position[1]
# Set the laser image when the spaceship fires
for i in range(50):
screen.blit(laser_image,[mouse_x + laser_x_vector,mouse_y + laser_x_vector])
laser_x_vector += 2
laser_x_vector += 2
# Clear the screen
screen.fill(WHITE)
#Limit to 20 sec
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
You fill the screen after you blit the lazer, so the lazer will not appear. You should fill before you blit the lazer so the lazer appears.
The others have already explained why you don't see the laser. Here's a working solution for you. First I suggest to use pygame.Rects for the positions of the lasers and put them into a list (rects can also be used for collision detection). Then iterate over these positions/rects in the main while loop, update and blit them. I also show you how to remove rects that are off screen.
import pygame
pygame.init()
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])
laser_image = pygame.Surface((10, 50))
laser_image.fill(GREEN)
done = False
clock = pygame.time.Clock()
laser_rects = []
laser_velocity_y = -20
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Turn the mouse position into a rect with the dimensions
# of the laser_image. You can use the event.pos instead
# of pygame.mouse.get_pos() and pass it as the `center`
# or `topleft` argument.
laser_rect = laser_image.get_rect(center=event.pos)
laser_rects.append(laser_rect)
remaining_lasers = []
for laser_rect in laser_rects:
# Change the y-position of the laser.
laser_rect.y += laser_velocity_y
# Only keep the laser_rects that are on the screen.
if laser_rect.y > 0:
remaining_lasers.append(laser_rect)
# Assign the remaining lasers to the laser list.
laser_rects = remaining_lasers
screen.fill(WHITE)
# Now iterate over the lasers rect and blit them.
for laser_rect in laser_rects:
screen.blit(laser_image, laser_rect)
pygame.display.flip()
clock.tick(30) # 30 FPS is smoother.
pygame.quit()

Python Pygame not showing image

I have problem, image "floor.png" is not showing on screen, blue color is showing. I was searching my old codes and I do everything same as in old working game.
But still image is invisible.
import pygame
pygame.init()
display_width = 600
display_height = 900
gameDisplay = pygame.display.set_mode((display_height, display_width))
pygame.display.set_caption("Parkour")
clock = pygame.time.Clock()
lightblue = (102, 255, 255)
floorImg = pygame.image.load("floor.png")
floorX = 300
floorY = 300
crashed = False
def DrawPictures(floorX, floorY):
gameDisplay.blit(floorImg, (floorX, floorY))
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
DrawPictures(floorX, floorY)
gameDisplay.fill(lightblue)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
Any help?
You blit the image on the screen surface correctly, but you just fill the screen afterwards. Just switch
DrawPictures(floorX, floorY)
gameDisplay.fill(lightblue)
to
gameDisplay.fill(lightblue)
DrawPictures(floorX, floorY)
FIX:
Problem is in the image not in code, I tried another image and the image worked ...

Categories