文章目录
- 步骤
- 1、创建`stick_figure.py`,代码:
- 运行代码,效果
用turtle包即可。
步骤
1、创建stick_figure.py,代码:
importturtleimporttime# --- 1. 设置画布 ---screen=turtle.Screen()screen.title("Python 火柴人行走动画")screen.bgcolor("lightcyan")# 背景颜色screen.setup(800,400)# 窗口大小screen.tracer(0)# 关闭自动刷新(为了实现流畅动画)# 创建画笔t=turtle.Turtle()t.hideturtle()t.pensize(3)t.color("black")# --- 2. 定义绘制火柴人的函数 ---defdraw_stickman(x,y,leg_offset,arm_offset):""" x, y: 身体中心坐标 leg_offset: 腿部摆动角度偏移 (用于走路效果) arm_offset: 手臂摆动角度偏移 """t.penup()t.goto(x,y)t.setheading(0)# 重置方向# A. 画头t.penup()t.goto(x,y+60)# 头部位置t.pendown()t.circle(20)# 半径20的头# B. 画身体t.penup()t.goto(x,y+40)t.pendown()t.goto(x,y-40)# 身体长度80# C. 画手臂 (左右交替)# 左臂t.penup()t.goto(x,y+30)# 肩膀位置t.setheading(180-arm_offset)# 向左摆动t.pendown()t.forward(30)# 右臂t.penup()t.goto(x,y+30)t.setheading(arm_offset)# 向右摆动t.pendown()t.forward(30)# D. 画腿 (左右交替,模拟走路)# 左腿t.penup()t.goto(x,y-40)# 胯部位置t.setheading(270-leg_offset)# 左腿向后/前蹬t.pendown()t.forward(40)# 右腿t.penup()t.goto(x,y-40)t.setheading(270+leg_offset)# 右腿向前/后蹬t.pendown()t.forward(40)# --- 3. 动画主循环 ---try:whileTrue:# 这里的逻辑是:让火柴人在屏幕上从左边移动到右边# 为了演示方便,我们让它在一个范围内来回走,或者一直往右走forstepinrange(0,360,10):# 控制步数# 计算位置:让火柴人从左(-300)走到右(300)# 如果超出屏幕,就回到左边current_x=-350+step*2ifcurrent_x>350:current_x=-350# 清除上一帧的画面t.clear()# 计算走路时的肢体摆动 (正弦波原理的简化版)# 通过取模运算 % 来实现左右腿交替walk_cycle=step%60leg_angle=0arm_angle=0ifwalk_cycle<30:# 第一阶段:左腿前,右腿后leg_angle=30arm_angle=30# 手臂与腿相反else:# 第二阶段:右腿前,左腿后leg_angle=-30arm_angle=-30# 调用绘图函数# 注意:手臂摆动方向和腿是相反的(左手配右脚),这样才自然draw_stickman(current_x,0,-leg_angle,arm_angle)# 刷新屏幕screen.update()time.sleep(0.05)# 控制速度exceptturtle.Terminator:print("窗口已关闭")运行代码,效果
实际效果是一个动图,这里只贴下图片了。