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

Recommended Answers

All 2 Replies

Hi!

Well, at least it's an interesting way to do it :)

Because Python is an OO language, I would probably have a class Monster and an instance-variable self.current_direction. I think this would be cleaner.

Regards, mawe

I think you're right. The problem I was having was a disconnect between the direction and the dx, dy. The better solution is, IMO,

def get_direction(self):
   return self._direction

def set_direction(self, value):
  self._direction = value
  dx,dy = {UP:  (0,-1),
           LEFT: (-1,0),
           DOWN: (0,1),
           RIGHT:(1,0)} [self._direction]

direction = property(get_direction, set_direction)

Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.