运行代码后,会在画布上画出一些大小不同、位置随机的白色星星,就像是一幅星空一样。你可以根据自己的需求修改代码,调整画布大小、星星数量和大小等参数,让画出来的星空更加逼真。
效果如图所示
import turtle
import random
turtle.setup(800, 600)
turtle.bgcolor('black')
def draw_star(x, y, size):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color('white')
turtle.begin_fill()
for i in range(5):
turtle.forward(size)
turtle.right(144)
turtle.end_fill()
for i in range(50):
x = random.randint(-400, 400)
y = random.randint(-300, 300)
size = random.randint(5, 20)
draw_star(x, y, size)
turtle.hideturtle()
turtle.done()
import turtle
import random
turtle.setup(800, 600)
turtle.bgcolor('black')
def draw_star(x, y, size):
"""
画星星的函数
:param x: 星星的x坐标
:param y: 星星的y坐标
:param size: 星星的大小
"""
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color('white')
turtle.begin_fill()
for i in range(5):
turtle.forward(size)
turtle.right(144)
turtle.end_fill()
for i in range(50):
x = random.randint(-400, 400)
y = random.randint(-300, 300)
size = random.randint(5, 20)
draw_star(x, y, size)
turtle.hideturtle()
turtle.done()