Advertisement
here2share

# tk_traveling_salesman.py

Dec 31st, 2022
1,282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. # tk_traveling_salesman.py
  2.  
  3. import tkinter as tk
  4. from math import sin, cos, pi, degrees, atan2
  5. from PIL import Image, ImageDraw, ImageFont
  6.  
  7. root = tk.Tk()
  8. root.title("tk_traveling_salesman")
  9.  
  10. ww, hh = 600, 600
  11. root.geometry(f"{ww}x{hh}+10+10")
  12.  
  13. canvas = tk.Canvas(root, width=ww, height=hh, bg="white")
  14. canvas.pack()
  15.  
  16. img = Image.new('RGB', (ww, hh), 'white')
  17. draw = ImageDraw.Draw(img)
  18. font = ImageFont.truetype("Gabriola.ttf", 1400)
  19. draw.text((10, -420), u"\u03C0", font=font, fill="#000000")
  20.  
  21. outline = []
  22. for x in range(img.width):
  23.     for y in range(img.height):
  24.         if img.getpixel((x, y)) != (255, 255, 255):
  25.             if max(img.getpixel((x0, y0)) for x0, y0 in ((x+1,y), (x-1,y), (x,y+1), (x,y-1))) == (255, 255, 255):
  26.                 outline.append((x, y))
  27.  
  28. # using the traveling salesman problem algorithm
  29. def calc_distance(point1, point2):
  30.     x1, y1 = point1
  31.     x2, y2 = point2
  32.     return ((x2-x1)**2 + (y2-y1)**2)**0.5
  33.  
  34. def traveling_salesman(outline):
  35.     remaining_points = outline
  36.     current_point = remaining_points[0]
  37.     remaining_points.remove(current_point)
  38.     path = [current_point]
  39.  
  40.     while len(remaining_points) > 0:
  41.         next_point = min(remaining_points, key=lambda x: calc_distance(current_point, x))
  42.         path.append(next_point)
  43.         remaining_points.remove(next_point)
  44.         current_point = next_point
  45.  
  46.     return path
  47.  
  48. sorted_outline = traveling_salesman(outline)
  49.  
  50. for x, y in sorted_outline:
  51.     canvas.create_rectangle(x, y, x+1, y+1, fill="#9433FF", width=0)
  52.     for i in '.'*400:
  53.         canvas.update()
  54.        
  55. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement