turtle库使用——漫天繁星+万花筒绘制

这里需要绘图窗口,关于绘图窗口的一些使用方法:

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

绘制效果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笨小古

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值