Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_circlepack2.py
- 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
- 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
- max_area=0
- circles=[]
- circles_max=[]
- exit=False
- gap=10
- pad=100
- XYO=list([(x,y) for x in range(pad, W-pad, 10) for y in range(pad, H-pad, 10)])
- random.shuffle(XYO)
- xy=XYO[:]*2
- t=5
- while True:
- if not t%5:
- 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+3:
- found_space=False
- break
- if found_space:
- num_circles=len(circles)
- circles.append(circle(x, y, num_circles))
- print num_circles
- break
- 0
- end=0
- area=0
- random.shuffle(circles)
- for c in circles:
- c.active=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
- wiggle=[(x+1,y-1),(x+1,y),(x+1,y+1)]
- wiggle += [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1)]
- random.shuffle(wiggle)
- for xyt in [(x,y)]+wiggle+[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:
- if c.radius > gap:
- c.x,c.y=xyt[0],xyt[1]
- c.active=1
- break
- elif c.radius > gap:
- c.radius -= 0.25
- if c.active and (c.radius < gap*5):
- c.radius += 0.2
- area += c.radius
- t+=1
- if area > max_area:
- max_area=area
- circles_max=circles[:]
- canvas.delete('all')
- for c in circles_max:
- create_circle(c.x,c.y,c.radius,fill='green')
- print num_circles, max_area
- root.update()
- print "All Circles Generated!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement