Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_circlepack.py ZZZ
- import random
- W, H=1200, 600
- HW, HH=W/2, H/2
- AREA=W*H
- try:
- import tkinter as tk
- except:
- import Tkinter as tk
- root=tk.Tk()
- root.title("Tk Circle Pack")
- canvas=tk.Canvas(root,width=W,height=H)
- canvas.pack(fill="both",expand=True)
- class circle:
- def __init__(self, x, y, id):
- self.x=x
- self.y=y
- self.radius=gap
- self.id=id
- self.active=10
- 0
- def create_circle(x, y, r, **kwargs): #center coordinates, radius
- x0=x-r
- y0=y-r
- x1=x+r
- y1=y+r
- return canvas.create_oval(x0, y0, x1, y1, **kwargs)
- 0
- def hyp(a,b):
- return (a**2+b**2)**0.5
- 0
- circles=[]
- exit=False
- gap=10
- pad=100
- xy=list([(x,y) for x in range(pad, W-pad, 10) for y in range(pad, H-pad, 10)])
- random.shuffle(xy)
- t=10
- while True:
- if not t%10:
- while xy:
- x,y=xy.pop()
- found_space=True
- for c in circles:
- distance=hyp(c.x-x, c.y-y)
- if distance <= c.radius+gap+2:
- found_space=False
- break
- if found_space:
- t=len(circles)
- circles.append(circle(x, y, t))
- print t
- break
- 0
- canvas.delete('all')
- end=1
- for c in circles:
- if not c.active:
- create_circle(c.x,c.y,c.radius,fill='green')
- continue
- else:
- create_circle(c.x,c.y,c.radius,fill='yellow')
- end=0
- for C in circles:
- if c.id == C.id: continue
- combined_radius=c.radius+C.radius
- x=c.x
- y=c.y
- # zzz xyt wiggles to further occupy space
- for xyt in [(x,y),(x+1,y),(x-1,y),(x,y+1),(x,y-1),(x+1,y+1),(x-1,y-1),(x+1,y-1),(x-1,y+1),0]:
- if xyt:
- if (pad < xyt[0] < W-pad) and (pad < xyt[1] < H-pad):
- distance_between_circles=hyp(xyt[0]-C.x, xyt[1]-C.y)
- if distance_between_circles > combined_radius+c.active+1:
- c.x,c.y=xyt[0],xyt[1]
- end=0
- break
- else:
- if c.active:
- c.active -= 1
- if c.active:
- c.radius += 0.1
- t+=1
- root.update()
- if end:
- break
- print "All Circles Generated!"
Add Comment
Please, Sign In to add comment