just for fun

Reply

Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 149
jrcagle jrcagle is offline Offline
Practically a Master Poster

just for fun

 
0
  #1
Feb 13th, 2007
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

  1. def get_direction(dx,dy):
  2.  
  3. dirs = {'dx == 0 and dy < 0': 'up', # in actual program, maps to self.UP == 0
  4. 'dx < 0 and dy == 0': 'left',
  5. 'dx == 0 and dy > 0': 'down',
  6. 'dx > 0 and dy == 0': 'right'}
  7.  
  8. for d in dirs:
  9. if eval(d):
  10. return dirs[d]
  11. return None
Last edited by jrcagle; Feb 13th, 2007 at 3:36 pm.
Reply With Quote Quick reply to this message  
Join Date: Sep 2005
Posts: 133
Reputation: mawe is an unknown quantity at this point 
Solved Threads: 58
mawe mawe is offline Offline
Junior Poster

Re: just for fun

 
0
  #2
Feb 13th, 2007
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
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 149
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: just for fun

 
0
  #3
Feb 13th, 2007
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,

  1.  
  2. def get_direction(self):
  3. return self._direction
  4.  
  5. def set_direction(self, value):
  6. self._direction = value
  7. dx,dy = {UP: (0,-1),
  8. LEFT: (-1,0),
  9. DOWN: (0,1),
  10. RIGHT:(1,0)} [self._direction]
  11.  
  12. direction = property(get_direction, set_direction)

Jeff
Last edited by jrcagle; Feb 14th, 2007 at 12:00 am.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC