In pygame, I am making a bootleg flappy bird and I am using classes for the pipes. I was wondering if there is a way to get the rect of a pipe in the list of pipes. I want to check for collisions between the bird and the pipe using the .colliderect() method. Here's the code to see what you are working with.
import pygame
pygame.init()
pygame.mixer.init()
music = pygame.mixer.music.load("audio/music.mp3")
flap = pygame.mixer.Sound("audio/flap.wav")
pygame.mixer.music.set_volume(0.05)
flap.set_volume(0.2)
pygame.mixer.music.play(-1)
clock = pygame.time.Clock()
running = True
level = 1
sw = 1080
sh = 700
bird_grav = 10
bird_jump = 200
screen = pygame.display.set_mode((sw,sh))
groundsurface = pygame.image.load("graphics/ground.png")
pipesurf = pygame.image.load("graphics/pipe.png")
groundrect = groundsurface.get_rect(midtop=(540,580))
bgoverlay = pygame.image.load("graphics/bgoverlay.png")
pygame.display.set_caption("Flap.")
index = 1
bgsurf = pygame.image.load("graphics/bg2.png")
class pipe:
def __init__(self,x,y):
self.x = x
self.y = y
self.img = pipesurf
self.piperect = self.img.get_rect(midbottom=(x,y))
self.rotimg = pygame.transform.rotate(self.img, 180)
self.rotimgrect = self.rotimg.get_rect(midtop=(x, y-700))
screen.blit(self.img, self.piperect)
screen.blit(self.rotimg, self.rotimgrect)
x = 50
y = 350
game_over = False
pipes = []
birdsurf = pygame.image.load("graphics/bird.png")
birdrect = birdsurf.get_rect(center=(x,y))
while running:
if level == 1:
if not game_over:
pipes.clear()
clock.tick(60)
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event == pygame.QUIT:
break
exit()
if event.type == pygame.MOUSEBUTTONUP:
pygame.mixer.Sound.play(flap)
y -= bird_jump
if event.type == pygame.KEYUP:
if event.key == pygame.K_b:
if index == 2:
index = 0
index = 1
if index == 1:
bgsurf = pygame.image.load("graphics/bg2.png")
if index == 2 or 0:
bgsurf = pygame.image.load("graphics/bg1.png")
birdsurf = pygame.image.load("graphics/bird.png")
birdrect = birdsurf.get_rect(center=(x,y))
screen.fill((128,217,255))
screen.blit(bgsurf, (0,0))
screen.blit(bgoverlay, (0,0))
pipes.append(pipe(300, 700))
pipes.append(pipe(500, 580))
pipes.append(pipe(700, 680))
pipes.append(pipe(900, 630))
if birdrect.colliderect():
print("test")
screen.blit(groundsurface, groundrect)
x = 10
y = bird_grav
screen.blit(birdsurf, birdrect)
pygame.display.update()
CodePudding user response:
See How do I detect collision in pygame?. colliderect()
Test for intersection of 2 rectangles. e.g.:
for aPipe in pipes:
if birdrect.colliderect(aPipe.piperect):
print("test")