Skip to content
Advertisement

How to detect collision between a list of Rect and another list of Rects

So I am making a zombie shooter game in pygame. I have a player – a zombie list – and a bullets list. all of them are rectangles.

I need to detect the collision between all the bullets and all zombies. – i tried colliderect but and collidelist but that is between a object and a list. I want a list and another list.

when i try doing:

def collide(self):
    for zombie in self.zombies:
        index = self.zombie.collidelist(self.bullets)
        if index:
            print("hit")

in zombie class it gives error TypeError: Argument must be a sequence of rectstyle objects.

https://github.com/tejasnarula/zombie-shooter

Advertisement

Answer

There is no function that can directly test for collisions between 2 lists of rectangles in pygame, unless you are using pygame.sprite.Group and pygame.sprite.groupcollide. If you have 2 pygame.sprite.Group objects (group1 and group2) you can do the following:

if pygame.sprite.groupcollide(group1, group2, True, True):
    print("hit")

If you have to lists of pygame.Rect objects (rect_list1 and rect_list2) you can use collidelist() or collidelistall() in a loop. e.g.:

for rect1 in rect_list1:
    index = rect1.collidelist(rect_list2)
    if index >= 0:
        print("hit")
for rect1 in rect_list1:
    collide_list = rect1.collidelistall(rect_list2)
    if collide_list:
        print("hit")

If you don’t have pygame.Rect objects, you need to create them and run the collision test in nested loops:

for zombie in self.zombies:
    zombieRect = pygame.Rect(zombie.x, zombie.y, zombie.width, zombie.height)
    for bullet in self.bullets:
        bulletRect = pygame.Rect(bullet.x, bullet.y, bullet.width, bullet.height)
        if zombieRect.colliderect(bulletRect):
            print("hit")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement