设置画布尺寸为1600*800,在其中填充随机圆形(半径为15至40,颜色随意),要求所有的圆形之间不重叠,并统计最多可以填充多少个。
//要自行下载turtle包哦
import turtle
import random
t = turtle.Pen()
# 速度最快
t.speed(0)
# 圆的颜色
colors = ["red", "blue", "yellow", "orange", "green", "gold", "purple", "pink"]
# 设置画圆的版面
w = 1600
h = 800
turtle.screensize(w, h, bg="black")
# turtle.setup(w+10,h+10)
# 确定画圆的起笔
def move(pos=(0, 0)):
t.penup()
t.goto(pos)
t.pendown()
# 画圆函数
def func1(pos=(0, 0), colorturtle="red", rturtle=30):
move(pos)
t.color(colorturtle)
t.begin_fill()
t.circle(rturtle)
t.end_fill()
# 用于计算两个圆心之间的距离:(((x1-x2)^2+(y1-y2)^2))^(1/2)
def distance(p1, p2):
d = ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
return d
circles = []
# 遍历判断是否可以在该院新下画圆
def measure(pos, rturtle):
for c in circles:
if distance(c[0], pos) < c[1] + rturtle:
return False
return True
cnt = 0
cnt1 = 0
# turtle.begin_fill()
for i in range(200000):
color = random.choice(colors)
r = random.randint(15, 40)
x = random.randint(-w // 2, w // 2)
y = random.randint(-h // 2, h // 2)
# 第一个if用于把整个圆控制在所设置屏幕范围内;第二个if遍历判断是否放得下该圆;
if x - r >= -(w / 2) and x + r <= (w / 2) and y - r >= -(h / 2) and y + r <= (h / 2):
if measure((x, y), r):
# cnt用于计数所方的圆个数;
cnt += 1
# 把圆的圆心坐标和半径放入链表circles中;func1函数用于画圆
circles.append([(x, y), r])
func1(pos=(x, -r + y), colorturtle=color, rturtle=r)
# else用于计数不满足画圆条件的次数
else:
cnt1 += 1
if cnt1 == 1000000:
break
# 输出所设置的屏幕能画的圆的个数
print(cnt)
turtle.done()