这里需要绘图窗口,关于绘图窗口的一些使用方法:
1.漫天繁星 —— 先写一个函数:在蓝色天空下绘制一颗星星,然后利用这个函数再加上随机函数就可以在天空绘制满满的星星了。
# 在蓝色天空下绘制漫天繁星
import turtle
import random
t = turtle.Pen()
t.screen.bgcolor('blue')
t.ht()
colorlist = ['yellow', 'white', 'gold', 'pink', 'gray', 'red', 'orange', 'aqua', 'green']
def stars(sides, size, cr, x, y):
t.penup()
t.goto(x, y)
t.pendown()
angle = 180 - (180 / sides)
t.color(cr)
t.begin_fill()
for x in range(sides):
t.forward(size)
t.right(angle)
t.end_fill()
while True:
ran_sides = random.randint(2, 5) * 2 + 1
ran_size = random.randint(5, 30)
ran_color = random.choice(colorlist)
ran_x = random.randint(-250, 250)
ran_y = random.randint(-250, 250)
stars(ran_sides, ran_size, ran_color, ran_x, ran_y)
绘制效果:
2.万花筒 —— 首先可以将背景设为黑色,然后自行设定绘制线条的长度和宽度,由于我这里设定的线条长度为100,所以这个程序必须让绘图起点在4边缩进超过100的位置,否则海龟会离开绘图区,最后只需设计无限循环即可。
# 万花筒
import turtle
import random
t = turtle.Pen()
length = 100
width = 10
t.pensize(width)
t.screen.bgcolor('black')
def is_inside():
""" 测试是否在绘制范围 """
left = (-t.screen.window_width() / 2) + 110 # 绘图区左边墙
right = (t.screen.window_width() / 2) - 110 # 绘图区右边区
top = (t.screen.window_height() / 2) - 110 # 绘图区上边墙
bottom = (-t.screen.window_height() / 2) + 110 # 绘图区下边墙
x, y = t.pos() # 获取海龟坐标
is_inside = (left < x < right) and (bottom < y < top)
return is_inside
def turtle_move():
colors = ['blue', 'pink', 'green', 'red', 'yellow', 'aqua']
t.color(random.choice(colors))
t.begin_fill()
if is_inside(): # 如果在绘布范围内
t.right(random.randint(0, 180))
t.forward(length)
else:
t.backward(length)
t.end_fill()
while True:
turtle_move()
绘制效果: