栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python入门】Turtle海龟库:利用海龟画笔交互绘制一个万花筒

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python入门】Turtle海龟库:利用海龟画笔交互绘制一个万花筒

利用海龟笔绘制一个螺旋线

功能要求

利用海龟笔绘制一个螺旋线

实例代码

import random

import turtle

turtle.bgcolor('pink')



t = turtle.Pen()

t.hideturtle()

colors = ['red', 'blue', 'yellow', 'green']

t.pencolor(random.choice(colors))

size = random.randint(10, 50)

t.penup()

t.goto(10,10)

t.pendown()

for i in range(size):

    t.forward(i)

    t.right(91)

turtle.done()

运行结果

 

 

程序一共运行了4次,每次的螺旋线的颜色不同,大小不同。

代码分析

import random:导入random模块。此模块用来生成随机数。

import turtle:导入turtle

turtle.bgcolor('pink'):将海龟布景设置为粉色。

t.hideturtle():隐藏小海龟。

colors = ['red', 'blue', 'yellow', 'green']:新建一个colors的列表,存放颜色。

t.pencolor(random.choice(colors)):设置海龟笔的颜色。颜色从列表colors中随机选取。random.choice(colors)表示从列表colors中随机取一个元素。

size = random.randint(10, 50):定义一个变量size。它的值为10~50的随机数。random.randint(10, 50)表示从10~50中随机去整数。

t.penup():将画笔抬起。

t.goto(10,10):将画笔移动到坐标(10, 10)位置。

t.pendown():将画笔落下。

for i in range(size):

    t.forward(i)

    t.right(91):for循环来实现绘制螺旋线。循环此时为变量size的值(即10~50之间的随机数)。这样设计可以实现绘制不同大小的螺旋线。

利用海龟笔绘制万花筒

功能要求

利用Python中的函数,提高代码的复用性,并制作一个万花筒。

说明:万花筒通过彩色随机螺旋线来实现。首先定义一个函数draw(),这个函数用来绘制一个螺旋线,函数中的画笔起始位置的坐标为函数的两个形参。然后调用函数的时候使用一个for循环来实现多次调用函数,同时,函数的两个实参由random模块生成的随机数组成。

实例代码

定义一个函数draw(),将上面的程序放入函数中,然后调用次函数。

import random

import turtle

turtle.bgcolor('pink')

t = turtle.Pen()

t.speed(0)

t.hideturtle()



def draw(x,y):

    colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'white', 'brown']

    t.pencolor(random.choice(colors))

    size = random.randint(10, 50)

    t.penup()

    t.goto(x,y)

    t.pendown()

    for i in range(size):

        t.forward(i)

        t.right(91)



for n in range(100):

    x = random.randint(-250, 250)

    y = random.randint(-250, 250)

    draw(x, y)

turtle.done()

运行结果

 

 

代码分析

def draw(x,y):

    colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'white', 'brown']

    t.pencolor(random.choice(colors))

    size = random.randint(10, 50)

    t.penup()

    t.goto(x,y)

    t.pendown()

    for i in range(size):

        t.forward(i)

        t.right(91):定义函数draw()。x和y为其两个参数。

t.goto(x,y):画笔移动的坐标设置为函数的两个形参。这样可以根据参数的变化实现不同位置的螺旋线。

for n in range(100):

    x = random.randint(-250, 250)

    y = random.randint(-250, 250)

    draw(x, y):函数调用部分的代码。使用for循环来调用100次函数。每次循环时,变量x和y都会取得一个“-250~250”之间的随机数,都会调用一次函数。

x = random.randint(-250, 250):从“-250~250”中随机取一个整数。

draw(x, y):用来调用函数,这里x和y是函数的实参,通过上面的赋值,x和y是两个整数

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号