Mar-05-2021, 09:29 PM
(This post was last modified: Mar-05-2021, 09:29 PM by deanhystad.)
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.
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.
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): 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 < abotI like that much better.