Can't get an image to have transparent background [duplicate] - python

This question already has answers here:
Pygame image transparency confusion
(1 answer)
How to convert the background color of image to match the color of Pygame window?
(1 answer)
Closed 1 year ago.
I am trying to import the image of a flappy bird, and even after .convert() or .convert_alpha() it's still not transparent? I flipped display right after converting, what am I missing?
import pygame
import os
from pipesforbird import Pipewall
pygame.init()
running = True
def player(x, y):
playerimg = pygame.image.load('birdo.png').convert()
screen.blit(playerimg, (x, y))
pygame.display.flip()
x = 50
y = 50
heigth = 60
width = 40
vel = 1
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
BLUE = (100, 100, 255)
BLACK = (0, 0, 0)
incomingpipes = pygame.sprite.Group()
greenPipewall = Pipewall(GREEN, 100, 300, 100)
greenPipewall.rect.x = 700
greenPipewall.rect.y = 0
secondPipewall2 = Pipewall(GREEN, 100, 400, -10)
secondPipewall2.rect.x = 1000
secondPipewall2.rect.y = 400
incomingpipes.add(greenPipewall)
incomingpipes.add(secondPipewall2)
while running:
screen = pygame.display.set_mode((800, 800))
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
y += vel
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
y -= (vel * 2)
if keys[pygame.K_ESCAPE]:
quit()
if y <= 100:
y = 100
if y >= 605:
y = 605
for Pipewall in incomingpipes:
Pipewall.moveLeft(vel)
if Pipewall.rect.x < -100:
Pipewall.rect.x = 800
screen.fill(BLUE)
incomingpipes.update()
incomingpipes.draw(screen)
pygame.draw.rect(screen, GREY, [0, 0, 800, 100], 0)
pygame.draw.rect(screen, GREY, [0, 650, 800, 200], 0)
player(x, y)
pygame.display.flip()
pygame.display.update()
quit()
this is the image in question (https://flyclipart.com/image-flappy-bird-png-767238)

Related

How to make entities take damage with color collision in pygame?

How do I make entities take damage with colors? I made a game with enemies shooting blue lasers and I want the player to take damage. And the player shoots a red laser. Upon detecting colors, I want a certain statement to be true. That would lower an entity's health by one. If color collision is a thing, it can be very useful for making many different games. Here is my code:
# importing packages
import pygame
import random
import time
import sys
# Initializing Pygame
pygame.init()
# Setting a display caption
pygame.display.set_caption("Space Invaders")
spaceship = pygame.image.load("spaceship2.png")
blue_enemy = pygame.image.load("blue_enemy.png")
green_enemy = pygame.image.load("green_enemy.png")
orange_enemy = pygame.image.load("orange_enemy.png")
pink_enemy = pygame.image.load("pink_enemy.png")
yellow_enemy = pygame.image.load("yellow_enemy.png")
# Creating a font
pygame.font.init()
font = pygame.font.SysFont("consolas", 30)
large_font = pygame.font.SysFont("consolas", 60)
small_font = pygame.font.SysFont("consolas", 20)
# Setting a display width and height and then creating it
display_width = 700
display_height = 500
display_size = [display_width, display_height]
game_display = pygame.display.set_mode(display_size)
intro_display = pygame.display.set_mode(display_size)
# Creating a way to add text to the screen
def message(sentence, color, x, y, font_type, display):
sentence = font_type.render(str.encode(sentence), True, color)
display.blit(sentence, [x, y])
def main():
global white
global black
global clock
# Spaceship coordinates
spaceship_x = 300
spaceship_y = 375
spaceship_x_change = 0
blue_enemy_health = 5
green_enemy_health = 5
orange_enemy_health = 5
pink_enemy_health = 5
yellow_enemy_health = 5
# Clock making
# Initializing pygame
pygame.init()
# Creating colors
red = (0, 0, 0)
blue = (0, 0, 255)
# clock stuff
clock = pygame.time.Clock()
time_elapsed_since_last_action = 0
time_elapsed_since_last_action2 = 0
time_elapsed_since_last_action3 = 0
# Creating a loop to keep program running
while True:
laser_rect = pygame.Rect(spaceship_x + 69, 70, 4, 310)
# --- Event Processing and controls
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
spaceship_x_change = 10
elif event.key == pygame.K_LEFT:
spaceship_x_change = -10
elif event.key == pygame.K_r:
red = (255, 0, 0)
elif time_elapsed_since_last_action2 > 250:
pygame.draw.rect(game_display, red, laser_rect)
time_elapsed_since_last_action2 = 0
elif event.type == pygame.KEYUP:
spaceship_x_change = 0
red = (0, 0, 0)
spaceship_x += spaceship_x_change
# Preventing the ship from going off the screen
if spaceship_x > display_width - 140:
spaceship_x -= 10
if spaceship_x < 1:
spaceship_x += 10
# Setting Display color
game_display.fill(black)
laser_coords = [70, 209, 348, 505, 630]
random_x_coord = random.choice(laser_coords)
dt = clock.tick()
time_elapsed_since_last_action += dt
if time_elapsed_since_last_action > 500:
pygame.draw.rect(game_display, blue, [random_x_coord, 85, 6, 305])
time_elapsed_since_last_action = 0
time_elapsed_since_last_action2 += dt
# Creating a spaceship, lasers, and enemies
game_display.blit(spaceship, (spaceship_x, spaceship_y))
message(str(blue_enemy_health), white, 65, 10, font, game_display)
game_display.blit(blue_enemy, (20, 25))
message(str(green_enemy_health), white, 203, 10, font, game_display)
game_display.blit(green_enemy, (160, 25))
message(str(orange_enemy_health), white, 341, 10, font, game_display)
game_display.blit(orange_enemy, (300, 25))
message(str(pink_enemy_health), white, 496, 10, font, game_display)
game_display.blit(pink_enemy, (440, 25))
message(str(yellow_enemy_health), white, 623, 10, font, game_display)
game_display.blit(yellow_enemy, (580, 25))
health = 10
message("Spaceship durability: " + str(health), white, 20, 480, small_font, game_display)
# Updating Screen so changes take places
pygame.display.update()
# Setting FPS
FPS = pygame.time.Clock()
FPS.tick(60)
black = (0, 0, 0)
white = (255, 255, 255)
gray = (100, 100, 100)
while True:
intro_display.fill(black)
pygame.event.poll()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
message("Space Bugs", white, 180, 150, large_font, intro_display)
if 150 + 100 > mouse[0] > 150 and 350 + 50 > mouse[1] > 350:
pygame.draw.rect(game_display, gray, [150, 350, 100, 50])
if click[0] == 1:
break
else:
pygame.draw.rect(game_display, white, [150, 350, 100, 50])
if 450 + 100 > mouse[0] > 450 and 350 + 50 > mouse[1] > 350:
pygame.draw.rect(game_display, gray, [450, 350, 100, 50])
if click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(game_display, white, [450, 350, 100, 50])
message("Start", black, 155, 360, font, intro_display)
message("Quit", black, 465, 360, font, intro_display)
# Go ahead and update the screen with what we've drawn.
pygame.display.update()
# Wrap-up
# Limit to 60 frames per second
clock = pygame.time.Clock()
clock.tick(60)
# Executing the function
if __name__ == "__main__":
main()
No, there is no such a "thing" as a "color collision". What color have the images? Are they uniformly colored? Most likely the pictures are only different in some details. A collision which checks for a uniform color is completely useless. A collision that also looks for a uniform color is almost useless.
If you detect a collision, you know the laser and the enemy. Hence, you know the color with which you represent them. All you have to do is do an additional check after the collision is detected.
Use pygame.sprite.Sprite to implement the objects. Add an attribute that indicates the color of the object:
class ColoredSprite(pygame.sprite.Sprite):
def __init__(self, x, y, image, color):
super().__init__()
self.image = image
self.rect = self.image.get_rect(center = (x, y)
slef.color = color
Manage the spites in pygame.sprite.Groups and use spritecollide to detect the collisions. Check the color attributes when a collision is detected
collide_list = sprite.spritecollide(sprite_group, False):
for other_sprite in collide_list:
if sprite.color == 'red' and other_sprite.color == 'blue':
# [...]
elif sprite.color == 'blue' and other_sprite.color == 'red':
# [...]
It is even possible to implement your own collision detection method and use it in combination with spritecollide by setting the optional collided argument:
def color_collision(sprite1, sprite2):
if sprite1.rect.colliderect(sprite2.rect):
return ((sprite1.color == 'red' and sprite2.color == 'blue') or
(sprite1.color == 'blue' and sprite2.color == 'red'))
return false
collide_list = sprite.spritecollide(sprite_group, False, color_collision):
for other_sprite in collide_list:
# [...]
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((250, 250))
sprite1 = pygame.sprite.Sprite()
sprite1.image = pygame.Surface((75, 75))
sprite1.image.fill('red')
sprite1.rect = pygame.Rect(*window.get_rect().center, 0, 0).inflate(75, 75)
sprite1.color = 'red'
sprite2 = pygame.sprite.Sprite()
sprite2.image = pygame.Surface((75, 75))
sprite2.image.fill('blue')
sprite2.rect = pygame.Rect(*window.get_rect().center, 0, 0).inflate(75, 75)
sprite2.color = 'blue'
all_group = pygame.sprite.Group([sprite2, sprite1])
def color_collision(sprite1, sprite2):
if sprite1.rect.colliderect(sprite2.rect):
return ((sprite1.color == 'red' and sprite2.color == 'blue') or
(sprite1.color == 'blue' and sprite2.color == 'red'))
return False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
sprite1.rect.center = pygame.mouse.get_pos()
collide = pygame.sprite.spritecollide(sprite1, all_group, False, color_collision)
window.fill(0)
all_group.draw(window)
for s in collide:
pygame.draw.rect(window, (255, 255, 255), s.rect, 5, 1)
pygame.display.flip()
pygame.quit()
exit()

How do I draw text onto the screen in pygame?

I'm trying to just draw any text on to the screen in pygame but when I run the program it just runs normally but no text appears on the screen. Is there something I'm doing wrong?
import pygame, random, sys
from pygame.locals import *
pygame.init()
#set constants
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 255)
FPS = 40
BLACK = (0,0,0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
#set variables
rectY1 = 200
rectY2 = 200
Y1change = 0
Y2change = 0
ballX = 320
ballY = 240
ballXvel = 0
ballYvel = 0
paddle1 = pygame.Rect(18,rectY1,10,100)
paddle2 = pygame.Rect(620,rectY2,10,100)
ball = pygame.Rect(ballX,ballY,30,30)
font = pygame.font.SysFont(None, 48)
#create shapes
def drawshapes():
pygame.draw.rect(DISPLAY, WHITE, paddle1)
pygame.draw.rect(DISPLAY, WHITE, paddle2)
pygame.draw.rect(DISPLAY, WHITE, ball)
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
#set up display
DISPLAY = pygame.display.set_mode((640,480),0,32)
pygame.display.set_caption('Pong')
fpsClock = pygame.time.Clock()
drawText('bruh', font, DISPLAY, (200), (200))
pygame.display.update
idk if this really is the loop you are talking about but here it is:
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 128 ))
#background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

how to generate random rectangles in a pygame and make them move like flappy bird?

I am a python beginner. I want to recreate chrome dino game. the random rectangle won't stop and the loop runs forever...please help me to stop the loop and make rectangles move.
Code:
import pygame
import random
pygame.init()
win = pygame.display.set_mode((500, 500))
#red rectangle(dino)
x = 20
y = 400
width = 30
height = 42
gravity = 5
vel = 18
black = (0, 0, 0)
#ground
start_pos = [0, 470]
end_pos = [500, 470]
#cactus
x1 = 20
y1 = 30
white = (2, 200, 200)
run = True
clock = pygame.time.Clock()
while run:
clock.tick(30)
pygame.time.delay(10)
win.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#random rectangle generation
for i in range(1):
width2 = random.randint(25, 25)
height2 = random.randint(60, 60)
top = random.randint(412, 412)
left = random.randint(300, 800)
rect = pygame.draw.rect(win, white, (left, top, width2,height2))
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
y = y - vel
else:
y = min(428, y + gravity)
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.draw.line(win, white, start_pos, end_pos, 2)
pygame.display.update()
pygame.display.flip()
pygame.quit()
pygame.draw.rect() des not "generate" a rectangle, it draws a rectangle on a surface.
pygame.Rect is a rectangle object. Create an instance of pygame.Rect before the main application loop:
obstracle = pygame.Rect(500, random.randint(0, 412), 25, 60)
Change the position of the rectangle:
obstracle.x -= 3
if obstracle.right <= 0:
obstracle.y = random.randint(0, 412)
And draw the rectangle to the window surface:
pygame.draw.rect(win, white, obstracle)
Example:
import pygame
import random
pygame.init()
win = pygame.display.set_mode((500, 500))
start_pos = [0, 470]
end_pos = [500, 470]
gravity = 5
vel = 18
black = (0, 0, 0)
white = (2, 200, 200)
hit = 0
dino = pygame.Rect(20, 400, 30, 40)
obstracles = []
number = 5
for i in range(number):
ox = 500 + i * 500 // number
oy = random.randint(0, 412)
obstracles.append(pygame.Rect(ox, oy, 25, 60))
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
dino.y -= vel
else:
dino.y = min(428, dino.y + gravity)
for obstracle in obstracles:
obstracle.x -= 3
if obstracle.right <= 0:
obstracle.x = 500
obstracle.y = random.randint(0, 412)
if dino.colliderect(obstracle):
hit += 1
win.fill(black)
color = (min(hit, 255), max(255-hit, 0), 0)
pygame.draw.rect(win, color, dino)
for obstracle in obstracles:
pygame.draw.rect(win, white, obstracle)
pygame.draw.line(win, white, start_pos, end_pos, 2)
pygame.display.update()
pygame.quit()

Python - Pygame - circular movement

I´ve the following code:
import pygame, sys, math
run = True
white = (255, 255, 255)
black = (0, 0, 0)
angle = 0
size = width, height = 800, 800
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
screen.fill(white)
while run:
msElapsed = clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill(white)
pygame.draw.circle(screen, black, (int(math.cos(angle) * 100), int(math.sin(angle) * 100)), 10)
pygame.display.flip()
angle += 0.05
pygame.quit()
this creates me a circle, which circles around the coordination (0, 0).
i want to move the center from (0, 0) to (100, 100).
Thank you in advance
Just add 100 to the x and y coordinates to adjust the center position:
x = int(math.cos(angle) * 100) + 100
y = int(math.sin(angle) * 100) + 100
pygame.draw.circle(screen, black, (x, y), 10)

Pygame - Moving rect between two points

I'm trying to make a rect move between two points in pygame. I've been able to make it move onto another rect and then stop, but then it won't move backwards, like it should.
I'm not sure what I'm doing wrong, so I decided to ask for help. Here's my code:
import pygame
width, height = 800, 600
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Test")
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
def gameloop():
lead_x1, lead_x2 = 1, 100
lead_y1, lead_y2 = 1, 1
velocity = 0.2
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
while not gameExit:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x1, lead_y1, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x2, lead_y2, block_size, block_size])
lead_x1 += velocity
if lead_x1 >= lead_x2:
lead_x1 += -velocity
if lead_x1 <= 0:
lead_x1 += velocity
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.display.update()
pygame.quit()
quit()
gameloop()
I think you need to place line lead_x1 += velocity inside the else statement, something like this:-
import pygame
width, height = 800, 600
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Test")
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
def gameloop():
lead_x1, lead_x2 = 1, 100
lead_y1, lead_y2 = 1, 1
velocity = 0.2
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
toogle_flag = 1
while not gameExit:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x1, lead_y1, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x2, lead_y2, block_size, block_size])
lead_x1 += toggle_flag * velocity
if lead_x1 >= lead_x2:
toggle_flag = -1*toggle_flag
if lead_x1 <= 0:
toggle_flag = -1*toggle_flag
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.display.update()
pygame.quit()
quit()
gameloop()
So what I am doing here is, let's take take a flag called toggle_flag, initialize it to 1.
Out box is at position 1, we add toggle_flag * velocity to our lead_x1. i.e we are basically adding velocity.
Once we touch the second box, we flip the value of toggle_flag to -1.
What will happen is, we keep on adding -velocity to our lead_x1.
Now, once we reach 0. We again flip the value of toggle_flag by multiplying it by -1, which we get us to add velocity to out lead_x1.
Hope this helps!

Categories

Resources