import matplotlib.pyplot as mpp
import os,random,math
#matplotlib.version=3.5.1,numpy.version=1.21.5
#创建画布及坐标轴
def set_cavans(width,height):
px = 1/mpp.rcParams['figure.dpi']
mpp.figure(figsize=(width*px,height*px))
mpp.axis([-width/2,width/2,-height/2,height/2])
#创建分区
def generate_area(width=500,height=400,standard1=100,standard2=100):
a,b=int(width/standard1),int(height/standard2)
area_lists=[]
for x_area in range(0,a):
x_min=int(-width/2+x_area*standard1)
x_max=int(-width/2+x_area*standard1+standard1)
for y_area in range(0,b):
y_max=int(height/2-y_area*standard2)
y_min=int(height/2-y_area*standard2-standard2)
temp=[x_min,y_min,x_max,y_max]
area_lists.append(temp)
return area_lists,a,b
#创建x,y坐标
def generate_coord(area_list):
coord=[]
x_min,y_min,x_max,y_max=area_list[0],area_list[1],area_list[2],area_list[3]
x_pos=random.randint(x_min+2,x_max-2)
y_pos=random.randint(y_min+2,y_max-2)
coord.append([x_pos,y_pos])
return coord
#绘制圆点
def generate_circle(area_lists):
i=0
x_gather,y_gather,pos_lists=[],[],[]
for area_list in area_lists:
i+=1
pos_list=generate_coord(area_list)
pos_lists=pos_lists+pos_list
word='A'+f'{i}'
mpp.text(pos_list[0][0],pos_list[0][1]+2,word,fontsize=6)
for x_y in pos_lists:
x_gather.append(x_y[0])
y_gather.append(x_y[1])
mpp.plot(x_gather,y_gather,'ro')
return pos_lists
#测量两点之间距离
def measure_distance(x1,y1,x2,y2):
x=(x1-x2)**2
y=(y1-y2)**2
distance=int(math.sqrt(x+y))
return distance
#两点连接并标距
def point_connect(a,b,color):
x1,y1,x2,y2=a[0],a[1],b[0],b[1]
mpp.plot([x1,x2],[y1,y2],color)
word=str(measure_distance(x1,y1,x2,y2))
mpp.text((x1+x2)/2+2,(y1+y2)/2+2,word,fontsize=8)
#绘制地图
def draw_map(pos_lists,a,b):
n=len(pos_lists)
color=['b-','g-','r-','c-','m-','y-','k-']
last_column=list(range(b-1,n,b))
last_row=list(range(n-b,n))
for i in range(0,n-1):
P=0
a_list=pos_lists[i]
for j in [i+1,i+b,i+b+1]:
if P<=1:
flag=random.randint(0,2)
if flag:
if i in last_column:
j=i+b
if i in last_row:
j=i+1
b_list=pos_lists[j]
x=random.randint(0,6)
point_connect(a_list,b_list,color[x])
P+=1
mpp.savefig('map.png')
mpp.show()
#主函数
width,height,standard1,standard2,=800,600,200,100
set_cavans(width,height)
area_lists,row,column=generate_area(width,height,standard1,standard2)
pos_lists=generate_circle(area_lists)
draw_map(pos_lists,row,column)
os.system('pause')