函数(那些东西有了一个名字)

本文介绍了如何使用Python的Turtle模块进行函数化编程,包括定义和调用函数以创建随机螺旋线和笑脸。同时,文章讲解了事件驱动的概念,如点击和键盘事件,展示了如何实现用户点击屏幕时在点击位置绘制图形,如笑脸和万花筒效果。最后,提出了编程挑战,即创建一个结合笑脸和万花筒效果的交互式应用。
摘要由CSDN通过智能技术生成

函数是带名字的代码块,用于完成具体的工作。

用函数整合内容

        定义函数random_spiral()

def random_spiral():
    t.pencolor(random.choice(colors))  
    size = random.randint(10,40)        
    x = random.randrange(-turtle.window_width()//2,
                         turtle.window_width()//2)
    y = random.randrange(-turtle.window_height()//2,
                         turtle.window_height()//2)
    t.penup()
    t.setpos(x,y)
    t.pendown()
    for m in range(size):
        t.forward(m*2)
        t.left(91)

        调用函数random_spiral()

在程序中直接输入:函数名(),就是调用函数 

random_spiral()

参数----传给函数

定义一个接收随机坐标并且在该坐标上绘制笑脸的函数,以参数形式接收坐标信息 

        在随机位置微笑

设计一个微笑

绘制脑袋

circle()方法是从底部逆时针绘制圆。

import turtle

t=turtle.Turtle()
t.pencolor("yellow")
t.fillcolor("yellow")
t.begin_fill()
t.circle(50)
t.end_fill()

 绘制眼睛

左眼:

import turtle

t=turtle.Turtle()
t.pencolor("yellow")
t.setpos(-15,60)
t.fillcolor("blue")
t.begin_fill()
t.circle(10)
t.end_fill()

右眼: 

import turtle

t=turtle.Turtle()
t.pencolor("yellow")
t.setpos(15,60)
t.fillcolor("blue")
t.begin_fill()
t.circle(10)
t.end_fill()

绘制嘴巴

import turtle

t=turtle.Turtle()
t.pencolor("yellow")
t.setpos(-25,40)
t.pencolor("black")
t.width(10)
t.goto(-10,20)
t.goto(10,20)
t.goto(25,40)
t.width(1)

 整合----在随机位置绘制微笑

只要把随机坐标x和y加到上述代码中代表坐标的地方,于是绘制随机微笑的函数如下:

def draw_smiley(x,y):      
    t.penup()
    t.setpos(x,y)
    t.pendown()
    # Head
    t.pencolor("yellow")
    t.fillcolor("yellow")
    t.begin_fill()
    t.circle(50)
    t.end_fill()
    # Left eye
    t.setpos(x-15, y+60)
    t.fillcolor("blue")
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Right eye
    t.setpos(x+15, y+60)
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Mouth
    t.setpos(x-25, y+40)
    t.pencolor("black")
    t.width(10)
    t.goto(x-10, y+20)
    t.goto(x+10, y+20)
    t.goto(x+25, y+40)
    t.width(1)

       在屏幕的50个随机位置绘制微笑

#RandomSmileys.py
import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")
def draw_smiley(x,y):      
    t.penup()
    t.setpos(x,y)
    t.pendown()
    # Head
    t.pencolor("yellow")
    t.fillcolor("yellow")
    t.begin_fill()
    t.circle(50)
    t.end_fill()
    # Left eye
    t.setpos(x-15, y+60)
    t.fillcolor("blue")
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Right eye
    t.setpos(x+15, y+60)
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Mouth
    t.setpos(x-25, y+40)
    t.pencolor("black")
    t.width(10)
    t.goto(x-10, y+20)
    t.goto(x+10, y+20)
    t.goto(x+25, y+40)
    t.width(1)
for n in range(50):
    x = random.randrange(-turtle.window_width()//2,
                         turtle.window_width()//2)
    y = random.randrange(-turtle.window_height()//2,
                         turtle.window_height()//2)
    draw_smiley(x,y)

运行结果:

 一些笑脸有部分在屏幕之外,通过对随机坐标进一步做些数学运算,保证笑脸在屏幕之内。 

    x = random.randrange(-turtle.window_width()//2+50,
                         turtle.window_width()//2-50)
    y = random.randrange(-turtle.window_height()//2,
                         turtle.window_height()//2-100)

返回----发回统计结果

        从函数返回一个值

def 函数名([参数...]):
    return 某个值

 例如:

#厘米转化为英寸
def convert_cm2in(cms):
    return cms / 2.54
#千克转换为磅,磅(英语:pound)是质量单位,简写为 lb
def convert_kg2lb(kgs):
    return kgs * 2.2

        在程序中使用返回值

""" 
计算用户的身高是乒乓球高度的多少倍和
用户的体重是乒乓球重量的多少倍 
"""

def convert_cm2in(cms):
    """ 厘米转化为英寸"""
    return cms / 2.54

def convert_kg2lb(kgs):
    """ 千克转换为磅,磅(英语:pound)是质量单位,简写为 lb """
    return kgs * 2.2

height_cm = int(input("输入你的身高(cm): "))
weight_kg = int(input("输入你的体重(kg): "))
height_in = convert_cm2in(height_cm)
weight_lb = convert_kg2lb(weight_kg)
#一个正规的乒乓球的高度是40毫米(1.57英寸),重量是2.7克(0.095盎司)
ping_pong_tall1 = round(height_cm / 4)
ping_pong_heavy1 = round(weight_kg * 1000 / 2.7)

ping_pong_tall2 = round(height_in / 1.57)
ping_pong_heavy2 = round(weight_lb * 16 / 0.095) #一磅等于16盎司

feet = height_in // 12
inch = height_in % 12

meter = height_cm // 100
cm = height_cm % 100

print("你的身高:", meter, "米", cm, "厘米, 你的体重:", weight_kg, 
      "公斤。")
print("你的身高:", feet, "英尺", inch, "英寸,你的体重: ", weight_lb, 
      "磅。")
print("你有", ping_pong_tall1, "个乒乓球高, ", ping_pong_heavy1, "个乒乓球重!")
print("你有", ping_pong_tall2, "个乒乓球高, ", ping_pong_heavy2, "个乒乓球重!")

交互简介

事件驱动app:由事件驱动程序的下一步动作。

事件处理程序:也叫事件监听程序,处理事件的程序。

        处理点击事件----TurtleDraw

回调函数:例如:调用函数b(a),a就是回调函数,a是函数名,不带括号,说明a没有被立即调用,程序继续运行,要待会再回过头来调用。

案例:将海龟的位置设置为用户点击的位置

# TurtleDraw.py
import turtle
t = turtle.Turtle()
t.speed(0)
turtle.onscreenclick(t.setpos)

        监听键盘事件----ArrowDraw

# ArrowDraw.py
import turtle
t = turtle.Pen()
t.speed(0)
t.turtlesize(2,2,2)
def up():
    t.forward(50)
def left():
    t.left(90)
def right():
    t.right(90)
turtle.onkeypress(up, "Up")
turtle.onkeypress(left, "Left")
turtle.onkeypress(right, "Right")
turtle.listen() #Set focus on TurtleScreen

        传递点击位置的坐标给回调函数----ClickSpiral

turtle.onscreenclick(回调函数名称):onscreenclick监听器把每次鼠标点击的x和y坐标传递给回调函数。

#ClickSpiral.py
"""在鼠标点击位置绘制螺旋线""" 
import random
import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange", "purple", 
          "white", "gray"]
def spiral(x,y):
    t.pencolor(random.choice(colors))  
    size = random.randint(10,40)        
    t.penup()
    t.setpos(x,y)
    t.pendown()
    for m in range(size):
        t.forward(m*2)
        t.left(91)
turtle.onscreenclick(spiral)

        在点击位置绘制笑脸----ClickAndSmile

#ClickAndSmile.py
import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")
def draw_smiley(x,y):
    t.penup()
    t.setpos(x,y)
    t.pendown()
    # Face
    t.pencolor("yellow")
    t.fillcolor("yellow")
    t.begin_fill()
    t.circle(50)
    t.end_fill()
    # Left eye
    t.setpos(x-15, y+60)
    t.fillcolor("blue")
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Right eye
    t.setpos(x+15, y+60)
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Mouth
    t.setpos(x-25, y+40)
    t.pencolor("black")
    t.width(10)
    t.goto(x-10, y+20)
    t.goto(x+10, y+20)
    t.goto(x+25, y+40)
    t.width(1)
turtle.onscreenclick(draw_smiley)

ClickKaleidoscope

让用户在点击位置绘制4条反射的螺旋线。

        draw_kaleido()函数

绘制4条反射的螺旋线

def draw_kaleido(x,y):
    t.pencolor(random.choice(colors))
    size = random.randint(10,40)
    draw_spiral(x,y, size)
    draw_spiral(-x,y, size)   
    draw_spiral(-x,-y, size)
    draw_spiral(x,-y, size)

        draw_spiral()函数

在指定位置绘制正方形螺旋线

def draw_spiral(x,y, size):
    t.penup()
    t.setpos(x,y)
    t.pendown()
    for m in range(size):
        t.forward(m*2)
        t.left(92)

        整合

#ClickKaleidoscope.py
import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange", "purple", 
          "white", "gray"]
def draw_kaleido(x,y):
    t.pencolor(random.choice(colors))
    size = random.randint(10,40)
    draw_spiral(x,y, size)
    draw_spiral(-x,y, size)   
    draw_spiral(-x,-y, size)
    draw_spiral(x,-y, size)
def draw_spiral(x,y, size):
    t.penup()
    t.setpos(x,y)
    t.pendown()
    for m in range(size):
        t.forward(m*2)
        t.left(92)
turtle.onscreenclick(draw_kaleido)

效果如下:

本章你应该掌握的能力

  • 将代码组织和分组到函数中
  • 使用def定义函数
  • 调用自己的函数
  • 定义和使用有参的函数
  • 编写有返回值的函数
  • 使用事件处理程序编写简单的交互式APP
  • 能够编写处理点击和按键事件的程序
  • 编写接受参数的事件处理函数

编程挑战

万花筒一样的笑脸

#ClickSmileKaleidoscope.py

import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor('black')

def draw_smilex(x,y):
    t.penup()
    t.setpos(x,y-100)
    t.pendown()
    # Face
    t.pencolor('yellow')
    t.fillcolor('yellow')
    t.begin_fill()
    t.circle(50)
    t.end_fill()
    # Left Eye
    t.setpos(x-15, y-80)
    t.fillcolor('blue')
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Right Eye
    t.setpos(x+15, y-80)
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Mouth
    t.penup()
    t.setpos(x-25,y-40)
    t.pendown()
    t.pencolor('black')
    t.width(10)
    t.goto(x-10, y-20)
    t.goto(x+10, y-20)
    t.goto(x+25, y-40)
    t.width(0)

def draw_smiley(x,y):
    t.penup()
    t.setpos(x,y)
    t.pendown()
    # Face
    t.pencolor('yellow')
    t.fillcolor('yellow')
    t.begin_fill()
    t.circle(50)
    t.end_fill()
    # Left Eye
    t.setpos(x-15, y+60)
    t.fillcolor('blue')
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Right Eye
    t.setpos(x+15, y+60)
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    # Mouth
    t.setpos(x-25,y+40)
    t.pencolor('black')
    t.width(10)
    t.goto(x-10, y+20)
    t.goto(x+10, y+20)
    t.goto(x+25, y+40)
    t.width(0)
    
def draw_kaleido(x,y):
    draw_smiley(x,y)
    draw_smiley(-x,y)   
    draw_smilex(-x,-y)
    draw_smilex(x,-y)

turtle.onscreenclick(draw_kaleido)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值