import random
# --- Helper Classes ---
class Point:
"""A simple 2D point."""
def __init__(self, x, y, data=None):
self.x = x
self.y = y
self.data = data # Optional payload (e.g., object ID, velocity)
def __repr__(self):
return f"P({self.x}, {self.y})"
class Rectangle:
"""Defines an Axis-Aligned Bounding Box (AABB)."""
def __init__(self, x, y, w, h):
self.x = x # Center X
self.y = y # Center Y
self.w = w # Half-width (distance from center to edge)
self.h = h # Half-height
def contains(self, point):
"""Checks if a point is within this rectangle."""
return (self.x - self.w <= point.x < self.x + self.w and
self.y - self.h <= point.y < self.y + self.h)
def intersects(self, range_rect):
"""Checks if this rectangle overlaps with another rectangle."""
return not (range_rect.x - range_rect.w > self.x + self.w or
range_rect.x + range_rect.w < self.x - self.w or
range_rect.y - range_rect.h > self.y + self.h or
range_rect.y + range_rect.h < self.y - self.h)
# --- Quadtree Class ---
class QuadTree:
def __init__(self, boundary, capacity=4):
"""
boundary: A Rectangle object defining the space this node covers.
capacity: Max points per node before splitting.
"""
self.boundary = boundary
self.capacity = capacity
self.points = [] # Points stored in this node
self.divided = False # Flag to check if split has occurred
def subdivide(self):
"""Creates 4 children quadtrees."""
x, y = self.boundary.x, self.boundary.y
w, h = self.boundary.w / 2, self.boundary.h / 2
# Define the 4 quadrants (NE, NW, SW, SE)
ne = Rectangle(x + w, y - h, w, h)
nw = Rectangle(x - w, y - h, w, h)
sw = Rectangle(x - w, y + h, w, h)
se = Rectangle(x + w, y + h, w, h)
self.northeast = QuadTree(ne, self.capacity)
self.northwest = QuadTree(nw, self.capacity)
self.southwest = QuadTree(sw, self.capacity)
self.southeast = QuadTree(se, self.capacity)
self.divided = True
def insert(self, point):
# 1. If point is not in this boundary, ignore
if not self.boundary.contains(point):
return False
# 2. If there is space, add point here
if len(self.points) < self.capacity:
self.points.append(point)
return True
# 3. If no space, subdivide (if not already done)
if not self.divided:
self.subdivide()
# 4. Try to add point to children
# (Since the point is guaranteed to be in self.boundary,
# it must fit into one of the children)
if self.northeast.insert(point): return True
if self.northwest.insert(point): return True
if self.southwest.insert(point): return True
if self.southeast.insert(point): return True
# This part should theoretically never be reached if logic is perfect
return False
def query(self, range_rect, found=None):
"""
Returns all points within the range_rect.
"""
if found is None:
found = []
# If the query range does not intersect this quad, return empty
if not self.boundary.intersects(range_rect):
return found
# Check points in this node
for p in self.points:
if range_rect.contains(p):
found.append(p)
# Recurse into children
if self.divided:
self.northwest.query(range_rect, found)
self.northeast.query(range_rect, found)
self.southwest.query(range_rect, found)
self.southeast.query(range_rect, found)
return found
# --- Demonstration ---
if __name__ == "__main__":
# 1. Setup the main boundary (Center 200,200 with width/height 200)
# This covers space from 0 to 400 on X and Y axes.
domain = Rectangle(200, 200, 200, 200)
qt = QuadTree(domain, capacity=4)
# 2. Insert random points
print("Inserting 50 random points...")
for i in range(50):
p = Point(random.randint(0, 400), random.randint(0, 400), data=f"ID_{i}")
qt.insert(p)
# 3. Perform a range query
# Let's search a small box in the top-left area
search_area = Rectangle(100, 100, 50, 50)
# This box is centered at 100,100.
# It covers X: 50->150, Y: 50->150.
print(f"\nSearching in area: Center(100,100), Size(100x100)...")
found_points = qt.query(search_area)
print(f"Found {len(found_points)} points:")
for p in found_points:
print(f" {p}")
# 4. Simple visualization logic (Text based)
def print_tree(node, indent=""):
print(f"{indent}Node ({len(node.points)} pts)")
for p in node.points:
print(f"{indent} {p}")
if node.divided:
print(f"{indent} Children:")
print_tree(node.northwest, indent + " ")
print_tree(node.northeast, indent + " ")
print_tree(node.southwest, indent + " ")
print_tree(node.southeast, indent + " ")
# Uncomment the line below to see the full tree structure
# print_tree(qt)