Advertisement
furas

Python - rectangles

Jun 11th, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. #/usr/bin/env python
  2.  
  3. class Point(object):
  4.  
  5.     def __init__(self, x, y):
  6.         self.x = x
  7.         self.y = y
  8.  
  9.  
  10. class Rect(object):
  11.  
  12.     def __init__(self, p1, p2):
  13.         '''
  14.        Store the top, bottom, left and right values for points
  15.        p1 and p2 are the (corners) in either order
  16.        '''
  17.         self.left   = min(p1.x, p2.x)
  18.         self.right  = max(p1.x, p2.x)
  19.         self.bottom = min(p1.y, p2.y)
  20.         self.top    = max(p1.y, p2.y)
  21.  
  22.  
  23. def overlap(r1,r2):
  24.     '''
  25.    Overlapping rectangles overlap both horizontally & vertically
  26.    '''
  27.    
  28.     hoverlaps = True
  29.     voverlaps = True
  30.    
  31.     if (r1.left > r2.right) or (r1.right < r2.left):
  32.         hoverlaps = False
  33.        
  34.     if (r1.top < r2.bottom) or (r1.bottom > r2.top):
  35.         voverlaps = False
  36.    
  37.     return hoverlaps and voverlaps
  38.  
  39. # --- main ---
  40.  
  41. rect1 = Rect(Point(0, 0), Point(15, 15))
  42. rect2 = Rect(Point(10, 10), Point(20, 20))
  43.  
  44. result = overlap(rect1, rect2)
  45.  
  46. print(result)
  47.  
  48. rect1 = Rect(Point(0, 0), Point(10, 10))
  49. rect2 = Rect(Point(15, 15), Point(20, 20))
  50.  
  51. result = overlap(rect1, rect2)
  52.  
  53. print(result)
  54.  
  55. rect1 = Rect(Point(5, 0), Point(10, 15))
  56. rect2 = Rect(Point(0, 5), Point(15, 10))
  57.  
  58. result = overlap(rect1, rect2)
  59.  
  60. print(result)
  61.  
  62. rect1 = Rect(Point(0, 0), Point(10, 10))
  63. rect2 = Rect(Point(15, 0), Point(20, 10))
  64.  
  65. result = overlap(rect1, rect2)
  66.  
  67. print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement