- 我是初学者..所以我不确定如何确保雪花不会重叠。谢谢!
import turtle
turtle.right(90)
turtle.penup()
turtle.goto(-700,300)
turtle.pendown()
def snowflakebranch(n):
turtle.forward(n*4)
for i in range(3):
turtle.backward(n)
turtle.right(45)
turtle.forward(n)
turtle.backward(n)
turtle.left(90)
turtle.forward(n)
turtle.backward(n)
turtle.right(45)
def snowflake(n):
for i in range(8):
snowflakebranch(n)
turtle.backward(n)
turtle.right(45)
import random
turtle.colormode(255)
turtle.tracer(0)
for i in range(35):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
turtle.color(r, g, b)
x = random.randint(-500, 500)
y = random.randint(-500, 500)
d = random.randint(6, 16)
snowflake(d)
turtle.penup()
turtle.goto(x, y)
#turtle.forward(250)
turtle.pendown()
turtle.update()
答案 0 :(得分:1)
一种方法是计算每个雪花的边界矩形(或圆)。将它们保存为列表或集合。无论何时计划制作新的雪花,首先要检查其边界矩形(或圆形)是否与之前任何雪花的边界重叠。如果是,请不要绘制它。如果没有,请绘制它并保存其边界。这种方法的概述不完整:
import turtle
import random
def snowflakebranch(n):
turtle.forward(n * 4)
for _ in range(3):
turtle.backward(n)
turtle.right(45)
turtle.forward(n)
turtle.backward(n)
turtle.left(90)
turtle.forward(n)
turtle.backward(n)
turtle.right(45)
def snowflake(n):
for _ in range(8):
snowflakebranch(n)
turtle.backward(n)
turtle.right(45)
def overlapping(bounds_list, bounds):
for previous in bounds_list:
if overlap(previous, bounds):
return True
return False
def overlap(b1, b2):
# return True or False if these two rectanges or circles overlap
pass
turtle.penup()
turtle.colormode(255)
turtle.tracer(0)
previous_bounds = []
i = 0
while i < 35:
x = random.randint(-500, 500)
y = random.randint(-500, 500)
turtle.goto(x, y)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
turtle.color(r, g, b)
turtle.pendown()
d = random.randint(6, 16)
# work out the bounding rectangle or circle based on 'd', 'x' & 'y'
# e.g. (x, y, width & height) or (x, y, radius)
bounds = ( ... )
if not overlapping(previous_bounds, bounds):
snowflake(d)
turtle.update()
previous_bounds.append(bounds)
i += 1
turtle.penup()
turtle.done()
使用上述逻辑和边界圆圈显示非重叠雪花的图像:
我其实喜欢你重叠雪花的样子。即使你想要重叠,上面的逻辑也可以让你控制多少重叠。