Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_traveling_salesman.py
- import tkinter as tk
- from math import sin, cos, pi, degrees, atan2
- from PIL import Image, ImageDraw, ImageFont
- root = tk.Tk()
- root.title("tk_traveling_salesman")
- ww, hh = 600, 600
- root.geometry(f"{ww}x{hh}+10+10")
- canvas = tk.Canvas(root, width=ww, height=hh, bg="white")
- canvas.pack()
- img = Image.new('RGB', (ww, hh), 'white')
- draw = ImageDraw.Draw(img)
- font = ImageFont.truetype("Gabriola.ttf", 1400)
- draw.text((10, -420), u"\u03C0", font=font, fill="#000000")
- outline = []
- for x in range(img.width):
- for y in range(img.height):
- if img.getpixel((x, y)) != (255, 255, 255):
- 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):
- outline.append((x, y))
- # using the traveling salesman problem algorithm
- def calc_distance(point1, point2):
- x1, y1 = point1
- x2, y2 = point2
- return ((x2-x1)**2 + (y2-y1)**2)**0.5
- def traveling_salesman(outline):
- remaining_points = outline
- current_point = remaining_points[0]
- remaining_points.remove(current_point)
- path = [current_point]
- while len(remaining_points) > 0:
- next_point = min(remaining_points, key=lambda x: calc_distance(current_point, x))
- path.append(next_point)
- remaining_points.remove(next_point)
- current_point = next_point
- return path
- sorted_outline = traveling_salesman(outline)
- for x, y in sorted_outline:
- canvas.create_rectangle(x, y, x+1, y+1, fill="#9433FF", width=0)
- for i in '.'*400:
- canvas.update()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement