small-projects/bounding-box-thing/test2.py
2025-04-05 18:26:40 -05:00

84 lines
2.7 KiB
Python

import pygame
import sys
# Initialize Pygame and create window
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Freehand Drawing with Debug Info")
font = pygame.font.Font(None, 24)
clock = pygame.time.Clock()
# Data structures
shapes = [] # List of completed shapes; each is a dict with points and bbox
drawing = False
current_points = [] # List of points for the stroke being drawn
def compute_bounding_box(points):
if not points:
return None
xs = [p[0] for p in points]
ys = [p[1] for p in points]
min_x, max_x = min(xs), max(xs)
min_y, max_y = min(ys), max(ys)
return (min_x, min_y, max_x - min_x, max_y - min_y)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Begin drawing on mouse button down
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
drawing = True
current_points = [event.pos]
# Append points as the mouse moves while drawing
elif event.type == pygame.MOUSEMOTION and drawing:
current_points.append(event.pos)
# Finish the current stroke on mouse button release
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
drawing = False
bbox = compute_bounding_box(current_points)
shapes.append({
"points": current_points,
"bbox": bbox
})
current_points = []
# Clear screen
screen.fill((30, 30, 30))
# Draw completed shapes in white
for shape in shapes:
if len(shape["points"]) > 1:
pygame.draw.lines(screen, (255, 255, 255), False, shape["points"], 2)
if shape["bbox"]:
pygame.draw.rect(screen, (255, 255, 255), shape["bbox"], 1)
# Draw current shape (freehand drawing) in green
if drawing and current_points:
if len(current_points) > 1:
pygame.draw.lines(screen, (0, 255, 0), False, current_points, 2)
bbox = compute_bounding_box(current_points)
if bbox:
pygame.draw.rect(screen, (0, 255, 0), bbox, 1)
# Debug Menu Info
debug_lines = [
f"Drawing: {drawing}",
f"Current Points: {len(current_points)}",
f"Shapes drawn: {len(shapes)}"
]
if current_points:
bbox = compute_bounding_box(current_points)
debug_lines.append(f"Bounding Box: {bbox}")
# Render debug text
y_offset = 10
for line in debug_lines:
text_surface = font.render(line, True, (255, 255, 255))
screen.blit(text_surface, (10, y_offset))
y_offset += text_surface.get_height() + 5
pygame.display.flip()
clock.tick(60)