Day 19 – 实例、状态和高级函数

Day 19 – 实例、状态和高级函数

温馨提示:本文最后更新于2024-12-24 14:24:26,某些文章具有时效性,若有错误或已失效,请在下方留言

事件监听

turtle模块的事件监听,通过 screenlisten 方法实现。

from turtle import Turtle, Screen

tim = Turtle()
screen = Screen()

def move_forward():
    tim.forward(100)

# 监听屏幕输入
screen.listen()
# 监听到空格,执行move_forward方法
screen.onkey(move_forward, "space")

# 点击屏幕才退出
screen.exitonclick()

实现的效果,如下所示

高级函数

函数可以作为另一个函数的输入参数,如下所示

# 函数定义
def function_a():
	# 

def function_b(func)
	# Do Something with func

# 函数定义
function_b(function_a)
	# 

对象状态及实例

一个可以创建几个不同的对象,这些对象成为实例。不同的实例之间相互独立,可以拥有不同的属性。

类、对象与实例

乌龟赛跑

turtle模块的坐标系原点(0,0)位于中心,水平方向为 X 轴,垂直方向为 Y 轴,如下所示

turtle 坐标系

具体的实现

from turtle import Turtle, Screen
import random

screen = Screen()
# 设置窗口的大侠
screen.setup(width=500, height=400)
# 弹窗邀请用户竞猜
bet =  screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")

colors = ["red", "orange", "yellow", "green", "blue", "purple"]

turtle_list = []
for index, color in enumerate(colors):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(color)
    new_turtle.penup()
    new_turtle.goto(-230, -120 + index * 50)
    turtle_list.append(new_turtle)

is_race_on = False

if bet:
    is_race_on = True

while is_race_on:
    for turtle in turtle_list:
        if turtle.xcor() > 230:
            print(turtle.pencolor())
            is_race_on = False
            if bet == turtle.pencolor():
                print(f"You have won! The {turtle.pencolor()} is the winner!")
            else:
                print(f"You have lost! The {turtle.pencolor()} is the winner!")
        turtle.forward(random.randint(1, 10))

screen.exitonclick()

最终的绘制效果,如下所示

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容