Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Point:
- def __init__(self, (x, y) = (0, 0)):
- self.x = x
- self.y = y
- class Rectangle:
- """A rectangle
- Attributes:
- x: Abscissa of the top-left corner of the rectangle.
- y: Ordinate of the top-left corner of the rectangle.
- w: Width. Should be >= 0.
- h: Height. Should be >= 0.
- """
- def __init__(self, x = 0, y = 0, w = 0, h = 0):
- self.x = x
- self.y = y
- self.w = w
- self.h = h
- def diagonal(self):
- "Returns the diagonal of the rectangle."
- return math.sqrt(self.w ** 2 + self.h ** 2)
- def surface(self):
- "Returns the surface of the rectangle."
- return self.w * self.h
- def is_null(self):
- return self.surface() == 0
- def origin(self):
- "Returns the coordinates for the top-left corner."
- return (self.x, self.y)
- def end(self):
- "Returns the coordinates for the bottom-right corner."
- return (self.x + self.w, self.y + self.h)
- def p1(self):
- return self.origin()
- def p2(self):
- return (self.x + self.w, self.y)
- def p3(self):
- return (self.x, self.y + self.h)
- def p4(self):
- return self.end()
- def points(self):
- "Returns a tuple of the corner points for this rectangle."
- return (self.p1(), self.p2(), self.p3(), self.p4())
- def contains(self, x, y):
- "Returns whether the given point is contained within the rectangle."
- return x in range(self.x, self.x + self.w) and y in range(self.y, self.y + self.h)
- def overlaps(self, other):
- "Returns whether both rectangles overlap."
- my_points = self.points()
- other_points = other.points()
- for p in self.points():
- if other.contains(p[0], p[1]):
- return True
- for p in other.points():
- if self.contains(p[0], p[1]):
- return True
- return False
- def __lt__(self, other):
- return self.surface() < other.surface()
- def __le__(self, other):
- return self < other or self == other
- def __eq__(self, other):
- return not self < other and not other < self
- def __ne__(self, other):
- return not self == other
- def __gt__(self, other):
- return other < self
- def __ge__(self, other):
- return other < self or self == other
- def __str__(self):
- return "(%d, %d) %dx%d" % (self.x, self.y, self.w, self.h)
Advertisement
Add Comment
Please, Sign In to add comment