I'm re-creating the classic PacMan for the fun of it and needed a way to translate back and forth between directions and dx, dy for a sprite. Here was a fun solution that avoided cumbersome if...elif...elif...elif... chains. Any thoughts on readability, efficiency? Specifically, if this gets called by 4 monsters and 1 pacman every clock-tick = 1/60 sec, am I likely to run into trouble?
Jeff
def get_direction(dx,dy):
dirs = {'dx == 0 and dy < 0': 'up', # in actual program, maps to self.UP == 0
'dx < 0 and dy == 0': 'left',
'dx == 0 and dy > 0': 'down',
'dx > 0 and dy == 0': 'right'}
for d in dirs:
if eval(d):
return dirs[d]
return None