Python Forum
how do i find the canvas location of an object?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how do i find the canvas location of an object?
#7
You're right, that is an ugly function. My logic was testing if a and b did not collide and returned the appropriate boolean value. It is sloppy coding using True and False instead returning the result of the comparison. To fix that I need to invert the logic. I could use not.
def collide(self, object):
    a = self.bounds()
    b = object.bounds()
    return not(b[0] > a[2] or b[2] < a[0] or b[1] > a[3] or b[3] < a[1])
That looks a little awkward, but it is better than before.

The bounding box is (left, top, right, bottom). The function does not make it clear that a[0] is a left. In Python it is easy to extract values from a collection. How does this function look if I replace indexing with more readable variable names.
def collide(self, object):
    aleft, atop, aright, abot = self.bounds()
    bleft, btop, bright, bbot = object.bounds()
    return not(bleft > aright or bright < aleft or btop > abot or bbot < atop)
That looks better, but there is still that ungainly not(). Lets get rid of that by inverting the logic.

bleft <= aright and bright >= aleft and btop <= abot and bbot >= atop

If I allow the ships to just touch without calling that a collision, I can shorten the expression a bit (drop the "="). I think I'll also change the order in the comparison to make it read better.
def collide(self, object):
    aleft, atop, aright, abot = self.bounds()
    bleft, btop, bright, bbot = object.bounds()
    return aleft < bright and atop < bbot and bleft < aright and btop < abot
I like that much better.
Reply


Messages In This Thread
RE: how do i find the canvas location of an object? - by deanhystad - Mar-05-2021, 09:29 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Resizing image inside Canvas (with Canvas' resize) Gupi 2 25,246 Jun-04-2019, 05:05 AM
Last Post: Gupi
  [Tkinter] Problem loading an image from directory into a Canvas object tiotony 3 3,954 Sep-02-2018, 06:47 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020