This may seem trivial but I Googled it and found no relevant results. And I don't have access to ChatGPT because unfortunately I was born in China.
I want to find out all the ways a polyline can pass through n*n evenly spaced lattice points without crossing itself.
Basically like a typical Android lock screen pattern, in which there are 9 points situated at the vertices of 4 adjacent congruent squares. And you can draw polylines that goes from vertices to other vertices.
I want to programmatically generate all such polylines that passes through all n*n (n >= 3 and n is integer) lattice points without intersecting itself, but to do that I need to first manually draw such polylines to find the mathematical pattern.
I can handle all the logics but I really don't know how to code GUI, basically I want a window that displays n*n lattice points arranged in a square, and you use mouse pointer to draw the polyline, the pointer auto-snaps to the grid, and you click and hold from one lattice to another to draw the lines.
How can I do that?
CodePudding user response:
If you just need to use it for visualization, you can just use PyGame. Here I just created a way to draw lines between points, which should be enough to get a better understanding.
Create window
import pygame
size = 500
pygame.init()
window = pygame.display.set_mode((size, size))
Create grid
n = 3
grid = []
for i in range(n):
for j in range(n):
grid.append((i*size//n size//n//2, j*size//n size//n//2))
Create and draw the lines
start_point = None
end_point = None
line_points = []
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
closest_point = min(grid, key=lambda x: ((x[0]-mouse_pos[0])**2 (x[1]-mouse_pos[1])**2)**0.5)
start_point = closest_point
elif event.type == pygame.MOUSEBUTTONUP:
mouse_pos = pygame.mouse.get_pos()
closest_point = min(grid, key=lambda x: ((x[0]-mouse_pos[0])**2 (x[1]-mouse_pos[1])**2)**0.5)
end_point = closest_point
line_points.append((start_point, end_point))
start_point = None
end_point = None
for point in grid:
pygame.draw.circle(window, (0, 0, 255), point, 10)
for start, end in line_points:
pygame.draw.line(window, (255, 0, 0), start, end, 5)
pygame.display.update()
pygame.quit()
Good luck with your project!