CMU Coding Bootcamp
1def rectanglesOverlap(
2 ax1: int, ay1: int, aw: float, ah: float, bx1: int, by1: int, bw: float, bh: float
3) -> bool:
4 """Check if two rectangles overlap."""
5 ax2 = ax1 + aw
6 ay2 = ay1 + ah
7 bx2 = bx1 + bw
8 by2 = by1 + bh
9 return (ax1 <= bx2 and ax2 >= bx1) and (ay1 <= by2 and ay2 >= by1)
10
11
12print("Testing rectanglesOverlap()...", end="")
13# Intersect at right of rectangle 1
14assert rectanglesOverlap(1, 1, 5, 1, 6, 1, 2, 2) == True
15# Intersect at top of rectangle 1
16assert rectanglesOverlap(1, 4, 5, 3, 1, 5, 8, 3) == True
17# Intersect at left of rectangle 1
18assert rectanglesOverlap(1, 5, 6, 6, -4, 7, 5, 3) == True
19# Intersect at bottom of rectanagle 1
20assert rectanglesOverlap(10, 10, 3, 3, 9, 7, 3, 3) == True
21# Partially overlapping rectangles
22assert rectanglesOverlap(1, 7, 3, 6, 3, 4, 2, 5) == True
23# Don't intersect
24assert rectanglesOverlap(1, 4, 3, 3, 10, 10, 5, 5) == False
25# Don't intersect, but x-coordinates overlap
26assert rectanglesOverlap(1, 4, 30, 3, 10, 10, 5, 5) == False
27# Don't intersect, but y-coordinates overlap
28assert rectanglesOverlap(1, 4, 3, 15, 10, 10, 5, 5) == False
29print("Passed!")