points = defaultdict(lambda:' ')
def triangle(p1,p2,p3):
p1,p2,p3 = sorted((p1,p2,p3),key = lambda p:p[1])#sort by y
sign = 1if p2[0]<p1[0] else -1
d = abs((p1[1]-p2[1])/(p1[1]-p3[1]))
M = ((1-d)*p1[0]+d*p3[0],p2[1])
_y = int(p2[1] - p1[1])
for y in range(int(p1[1]),int(p2[1]+1)):
if _y==0:
for x in range(int(p1[0]),int(p2[0]+1)):
points[(x,p1[1])] = '*'break
dx = p1[0]-p2[0]
dy = y-p1[1]
dxx = dy*dx/_y
dx2 = M[0] - p1[0]
dxx2 = dy*dx2/_y
for x in range(int(p1[0]-dxx),int(p1[0]+dxx2+sign),sign):
points[(x,y)] = '*'
_y = int(p3[1] - p2[1])
for y in range(int(p2[1]),int(p3[1]+1)):
if _y==0:
for x in range(int(p2[0]),int(p3[0])+1):
points[(x,p3[1])] = '*'break
dx = p3[0] - M[0]
dy = p3[1]-y
dxx = dx*dy/_y
dx2 = p3[0]-p2[0]
dxx2 = dx2*dy/_y
for x in range(int(p3[0]-dxx2),int(p3[0]-dxx+sign),sign):
points[(x,y)] = '*'
defkoch(p1,p2,p3,n,flag = True):
triangle(p1,p2,p3)
p = {(p1,p2),(p2,p3),(p1,p3)} if flag else {(p1,p3),(p2,p3)}
d = 1/3
all = {p1,p2,p3}
other = []
if n>1:
for (_p1,_p2) in p:
(x1,y1),(x2,y2) = _p1,_p2
x4 = (1-d)*x1+d*x2
y4 = (1-d)*y1+d*y2
x5 = d*x1+(1-d)*x2
y5 = d*y1+(1-d)*y2
(x3,y3) = tuple(all-{_p1,_p2})[0]
x6,y6 = get_point(x4,y4,x5,y5,x3,y3)
other.append((x6,y6))
koch((x4,y4),(x5,y5),(x6,y6),n-1,False)
x7 = (1-d)*p3[0]+d*p1[0]
y7 = (1-d)*p3[1]+d*p1[1]
x8 = (1-d)*p3[0]+d*p2[0]
y8 = (1-d)*p3[1]+d*p2[1]
koch((x7,y7),(x8,y8),p3,n-1,False)
if flag:
return other
defget_point(x1,y1,x2,y2,x,y):
mx,my = (x1+x2)/2,(y1+y2)/2
d1 = ((my-y1)**2+(mx-x1)**2)**(0.5)
k = (y2-y1)/(x2-x1)
dis,x3,y3 = 0,0,0for sign in (-1,1):
b = my+sign*(3**0.5)*d1/(1+k**2)**(0.5)
a = mx-(b-my)*k
dis,x3,y3 = max((dis,x3,y3),(((x-a)**2+(y-b)**2)**0.5,a,b))
return x3,y3
填充:
from PIL import Image,ImageDraw
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
for x inrange(width):
for y inrange(height):
if (x,y) in points:
draw.point((x, y), fill=(0,0,0))
image.save('code.jpg', 'jpeg')