diff --git a/thinkcspy/Chapter-17-18-Exercises/rectangle.py b/thinkcspy/Chapter-17-18-Exercises/rectangle.py index 4383467..4507c78 100644 --- a/thinkcspy/Chapter-17-18-Exercises/rectangle.py +++ b/thinkcspy/Chapter-17-18-Exercises/rectangle.py @@ -3,6 +3,11 @@ from points import Point class Rectangle: def __init__(self, pos, width, height): self.pos = pos + if width < 0: + width = 0 + if height < 0: + height = 0 + self.width = width self.height = height @@ -11,23 +16,15 @@ class Rectangle: self.lowerY = self.pos.getY() self.upperY = self.lowerY + self.height - if self.lowerX == self.upperX or self.lowerY == self.upperY: - return "Error: Rectangle not defined." - - if self.lowerX > self.upperX: - self.lowerX = self.upperX - self.upperX = self.pos.getX() - - if self.lowerY > self.upperY: - self.lowerY = self.upperY - self.upperY = self.pos.getY() - def getWidth(self): return self.width def getHeight(self): return self.height + def getCoords(self): + return [self.lowerX, self.lowerY, self.upperX, self.upperY] + def __str__(self): return "Lower Left Coordinates: {}; Width: {}; Height: {}".format(self.pos, self.width, self.height) @@ -57,17 +54,43 @@ class Rectangle: pnt = Point(self.width, self.height) return pnt.distanceFromOrigin() - def collission(self, pnt): - pntX = pnt.getX() - pntY = pnt.getY() + +def collission(r1, r2): + conditionW = False + conditionH = False + bigR = r1 + lilR = r2 - if (pntX > self.lowerX and pntX < self.upperX) or (pntY > self.lowerY and pntY < self.upperY): - return True + if r1.area() < r2.area(): + bigR = r2 + lilR = r1 - return False + lilArr = lilR.getCoords() + bigArr = bigR.getCoords() -r = Rectangle(Point(-10, 5), 4, 30) -#print(r) -print(r.collission(Point(10, 25))) -print(r.contains(Point(10, 25))) - \ No newline at end of file + # Compare widths and heights + if lilR.width > bigR.width: + if bigArr[0] in range(lilArr[0], lilArr[2] + 1) or bigArr[2] in range(lilArr[0], lilArr[2] + 1): + conditionW = True + elif lilArr[0] in range(bigArr[0], bigArr[2] + 1) or lilArr[2] in range(bigArr[0], bigArr[2] + 1): + conditionW = True + + if lilR.height > bigR.height: + if bigArr[1] in range(lilArr[1], lilArr[3] + 1) or bigArr[3] in range(lilArr[1], lilArr[3] + 1): + conditionH = True + elif lilArr[1] in range(bigArr[1], bigArr[3] + 1) or lilArr[3] in range(bigArr[1], bigArr[3] + 1): + conditionH = True + + if conditionW and conditionH: + return "Collission!" + + return "All safe for now." + + +r = Rectangle(Point(10, 25), 10, 0) +s = Rectangle(Point(10, 20), 10, 4) +# print(r) +# print(r.collission(Point(10, 25))) +# print(r.contains(Point(10, 25))) + +print(collission(r, s)) \ No newline at end of file