Skip to content

Instantly share code, notes, and snippets.

@jediminer543
Last active August 29, 2015 14:03
Show Gist options
  • Save jediminer543/29889764b8988476249e to your computer and use it in GitHub Desktop.
Save jediminer543/29889764b8988476249e to your computer and use it in GitHub Desktop.
Python colision detection
class Rectangle:
# defines x and y coords
x = 0
y = 0
# defines width and height values. these must be positive
w = 0
h = 0
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
def validate(self):
#checks that the rechangle has positive values
if not(y <= (y + h) or x <= (x + w)):
return False
# TODO more validation code
else:
return True
# determines if 2 rectangles are colliding
def colides(rect1, rect2):
# checks that both arguments are rectangles
if not(isinstance(rect1, Rectangle) and isinstance(rect2, Rectangle)):
raise ValueError("Must be instance of rectangle")
# checks that both arguments are valid rectangles
if not(rect1.validate() and rect2.validate()):
raise ValueError("Rectangles Supplied are invalid")
return (rect1.x > rect2.x) and (rect1.y > rect2.y) and ((rect2.x + rect2.w) > rect1.w) and ((rect2.y + rect2.h) > rect1.y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment