944,148 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 1185
  • Python RSS
Feb 13th, 2007
0

just for fun

Expand Post »
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

Python Syntax (Toggle Plain Text)
  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.
Similar Threads
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Feb 13th, 2007
0

Re: just for fun

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
Reputation Points: 19
Solved Threads: 58
Junior Poster
mawe is offline Offline
133 posts
since Sep 2005
Feb 13th, 2007
0

Re: just for fun

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,

Python Syntax (Toggle Plain Text)
  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.
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Tkinter Spreadsheet
Next Thread in Python Forum Timeline: wxPython: wx.RadioButtons SetValue has no affect in Linux





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC