1
votes

For my pygame tower defence program, I am trying to figure out how to implement collision with other towers that are already placed on the map.

The placement process creates a 48x48 preview sprite that moves in a grid on the players mouse when it is on the game screen. Tower sprites are kept in a group called tower_sprites. I have this bit of code to check if the sprite is colliding with certain terrain tiles and tower sprites (this is in the sprite update function):

if y < C.map_width and x < C.map_height: #if preview sprite coords are on the game screen (x and y are rounded coords of the preview tower at certain points as each tile is 16x16 while the tower is 48x48)
    if live_grid.tilemap[x][y] != 0: #if the coordinate is not grass
        self.map_collide.append(1)
    else:                            #if the coordinate is grass
        self.map_collide.append(0) 
    for sprite_object in tower_sprites:         #for each sprite in tower_sprites
        print (sprite_object)
        if sprite_object.rect.colliderect(self.rect):   #if the rect of the preview sprite collides with a tower sprites rect
            self.tower_collision = True
        else:
            self.tower_collision = False

The for loop onward section is meant to check if the preview sprite is colliding with any tower sprites rect. If so it sets a variable to true or otherwise, False.

The program then checks to see if self.tower_collision is true in a different function within the class and if so, returns a value back to the main game loop:

def collide_boolean(self):
    if 1 in self.map_collide: #for map collision
        del self.map_collide[:]
        return False #False = can't place

    if self.tower_collision == True: #for tower collision
        return False

    else:   #for map collision
        del self.map_collide[:]
        return True

The issue this code produces however is that it only checks if the last sprite the player placed collides with the preview sprite, and not others before it. I want the program to check all tower sprites but im not sure how to do this.

What do i need to do to change this? If you want a full dropbox of the program so far, just ask.

EDIT: Dropbox link https://www.dropbox.com/sh/ajwlkwufrxadoqo/AAASwxQPK8gFG-0zixfc2fC1a?dl=0

1
A minimal, complete and verifiable example would help us to find a solution. - skrx
Can you use the builtin pygame.sprite.collideany(..)? - import random

1 Answers

3
votes

Unless the sprite being collided with is the last one in tower_sprites, subsequent iterations through the loop will overwrite self.tower_collision with False again.