对科赫雪花的一个扩展--实现了随机位置,随机阶数,随机颜色,随机尺寸的功能
附上代码
一、随机阶数
def randomlevel():
level = random.randint(1, 4)
level = int(level)
return level
二、随机尺寸-随机位置
def randomSize():
size = random.randint(50, 100)
size = int(size)
return size
def randomDrawX():
x=random.randint(-500,500)
x=int(x)
return x
def randomDrawY():
y=random.randint(-300,300)
y=int(y)
return y
三、随机颜色
def randomcolor():
colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
color = ""
for i in range(6):
# 拼接字符串
color += colorArr\[random.randint(0,14)\]
return "#"+color
四、全部代码
import turtle,random
主函数
def koch(size, n):
if n == 0:
turtle.fd(size)
else:
for angle in [0, 60, -120, 60]:
turtle.left(angle)
koch(size/3, n-1)
随机阶数
def randomlevel():
level = random.randint(1, 4)
level = int(level)
return level
随机尺寸
def randomSize():
size = random.randint(50, 100)
size = int(size)
return size
随机位置
def randomDrawX():
x=random.randint(-500,500)
x=int(x)
return x
def randomDrawY():
y=random.randint(-300,300)
y=int(y)
return y
随机颜色
def randomcolor():
colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
color = ""
for i in range(6):
color += colorArr[random.randint(0,14)]
return "#"+color
def main():
turtle.setup(1200,700,100,100)
#设置画布背景颜色
turtle.screensize(bg="#F8F8FF")
turtle.pensize(1)
line = randomlevel()
size = randomSize()
numbers= random.choice(\[3, 4, 5, 6, 7, 8, 9,\])
for i in range(0,numbers):
turtle.penup()
x = randomDrawX()
y = randomDrawY()
turtle.color(randomcolor(),"white")
turtle.goto(x, y)
turtle.speed(2000)
turtle.pendown()
koch(size, line)
turtle.right(120)
koch(size, line)
turtle.right(120)
koch(size, line)
turtle.done()
turtle.hideturtle()
main()
五、效果图--每次运行生成不同的图像
最后说一声啊,这类似一个模板,可以随便修改颜色啥的。