import random
plt.figure(figsize=(20,15),dpi=80)
def F(x0,y0,n): #定義遞迴程式
if n<1:return
x1=x0+2**(n-1) ;y1=y0
x2=x0+2**n ;y2=y0
x3=x0 ;y3=y0+2**(n-1)
x4=x1 ;y4=y3
x5=x2 ;y5=y3
x6=x0 ;y6=y0+2**n
x7=x1 ;y7=y6
x8=x2 ;y8=y6
A=random.sample(bag,4)
if A[0]==0:
plt.plot([x3,x4],[y3,y4],color="green",linewidth=2)
if A[1]==0:
plt.plot([x4,x5],[y4,y5],color="green",linewidth=2)
if A[2]==0:
plt.plot([x1,x4],[y1,y4],color="green",linewidth=2)
if A[3]==0:
plt.plot([x4,x7],[y4,y7],color="green",linewidth=2)
if A[0]==1:
a=random.randint(x3,x4-1)
plt.plot([x3,a],[y3,y3],color="green",linewidth=2)
plt.plot([a+1,x4],[y3,y4],color="green",linewidth=2)
if A[1]==1:
a=random.randint(x4,x5-1)
plt.plot([x4,a],[y4,y4],color="green",linewidth=2)
plt.plot([a+1,x5],[y4,y5],color="green",linewidth=2)
if A[2]==1:
a=random.randint(y1,y4-1)
plt.plot([x1,x1],[y1,a],color="green",linewidth=2)
plt.plot([x1,x4],[a+1,y4],color="green",linewidth=2)
if A[3]==1:
a=random.randint(y4,y7-1)
plt.plot([x4,x4],[y4,a],color="green",linewidth=2)
plt.plot([x4,x7],[a+1,y7],color="green",linewidth=2)
F(x0,y0,n-1)
F(x1,y1,n-1)
F(x3,y3,n-1)
F(x4,y4,n-1)
#以下內容為主程式
(x0,y0,n)=(0,0,5) # n:2~5
bag=[1,1,1,0] #
F(x0,y0,n)
plt.plot([x0+1,x0+2**n,x0+2**n],[y0,y0,y0+2**n],color="blue",linewidth=5)
plt.plot([x0,x0,x0+2**n-1],[y0,y0+2**n,y0+2**n],color="blue",linewidth=5)
plt.plot(0.5,0,marker="D",color="red")
plt.plot(2**n-0.5,2**n,marker="D",color="red")
plt.text(0,-3,"START", fontsize=20)
plt.text(2**n-1,2**n+1,"END", fontsize=20)
plt.ylim(-5,2**n+5) #設定 y 軸的範圍
plt.show()