Python Forum
[PyGame] finding local area in dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] finding local area in dictionary
#1
I have a dictionary of tile sprites, (x,y) are the keys. I think I have found how to determine the tiles local to the player, but I get a KeyError when those tiles don't exist.

Is it best practice to use an Exception to pass, or is there some better way avoid the error?

def find_local(self):
        local = []
        pos = (self.rect.centerx // self.game.level.tilesize, self.rect.centery // self.game.level.tilesize)
        
        for x in range(pos[0] - 3, pos[0] + 3):
            for y in range(pos[1] - 3, pos[1] + 3):
                local.append(self.game.level.tile_dict[x, y])
        


The hope is that I can use this local list to prevent the player and bullets from checking collisions for tiles that are a million miles away.

Thanks for help.
Reply
#2
UPDATE:

I went with the try/except route. Works fine. I've used that local list for drawing and updating too. I discovered a fun fact. Using sprite.Group.update() on a huge group, even if most of the sprites in the group don't even have an update section is resource intensive. Who knew?! lol

Atom crashed when I tried to generate a 1000x1000 map, but 100x1000 worked and now with 100,000 tiles there is still no hint of lag. Pretty happy.
Reply
#3
key in dict -> return bool
99 percent of computer problems exists between chair and keyboard.
Reply
#4
You could use dict.get(key, value). This returns a special value (default is None) when the dictionary lookup fails. Here I make a list of all possible near tiles, then remove all missing tiles.
def find_local(self):
    x = self.rect.centerx // self.game.level.tilesize
    y = self.rect.centery // self.game.level.tilesize
    tiles = self.game.level.tile_dict
    return [t for t in [tiles.get((i, j)) for i in range(x-3, x+3) for j in range(y-3, y+3)] if t]
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020