--我是个初学者,所以我不知道如何确保雪花不会重叠。谢谢!

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()

最佳答案

一种方法是计算每个雪花的边界矩形(或圆)。将这些保存为列表或集合。每当您计划制作一个新的雪花时,首先检查它的边框(或圆圈)是否与以前的任何雪花的边框重叠。如果有,就不要画。如果它没有,画出来并保存它的边界。这种方法的不完整概述:

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()

使用上述逻辑和边界圆的非重叠雪花图像也将显示:
python - 在python中创建雪花时如何放置if and then语句-LMLPHP
我真的很喜欢你重叠的雪花。即使您想要重叠,上面的逻辑也允许您控制重叠的程度。

10-06 08:33