ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-Tutor
python-Tutor
[Tutor] Fastest (x,y) distance calculation
by Zak Arntson other posts by this author
Sep 10 2003 7:56PM messages near this date
[Tutor] Re: [pygame] Fastest (x,y) distance calculation | Re: [Tutor] Productivity
I'm using pygame, but the algorithm is basic enough to be cross-posted.

I have two classes, a Temple and a Mover class. Each have the a rect
attribute (which for non-pygamers, is an object represented by an
(x,y,width,height) tuple). Each Mover analyzes the list of Temples to find
the nearest one.

My Game class has the following method, called by each Mover during its
thinking phase. (non-pygamers: centerx and centery are the x & y values at
the center of the rect)

###
class Game:
    ...
    def get_nearest_temple(self, pos):
        distances = [((pos[0] - tmp.rect.centerx) ** 2 +
                      (pos[1] - tmp.rect.centery) ** 2,
                      tmp) for tmp in self.temples]

        return min(distances)[1]
    ...

###

It's basically taking advantage of the fact that:
    distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)
And for integer x & y values, I can square the right side of the equation
for purposes of distance comoparison.

I can't think of a better algorithm for getting the nearest object than
this. Profile tells me this is one of the slower parts of my code. Any
thoughts/suggestions?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Zak Arntson
Niki Spahiev
Raymond Hettinger

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved