You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Python Turtle的当前角度?用于DVD屏保开发

解决Python Turtle获取当前角度判断东/西方向的问题
  • 获取当前角度的方法:无论是使用全局turtle函数还是海龟实例,都可以通过heading()方法直接获取当前朝向角度。示例代码:

    import turtle
    
    # 全局调用方式
    current_angle = turtle.heading()
    
    # 实例化海龟对象调用
    t = turtle.Turtle()
    current_angle = t.heading()
    
  • 角度与方向的对应关系(默认标准坐标系模式):

    • 朝东:角度为0(或360的整数倍,如360、-360等)
    • 朝西:角度为180(或等价的-180、540等)
  • DVD屏保场景下的实用逻辑:
    实际制作屏保时,很少需要严格判断正朝东/西,更多是在海龟碰到左右边界时反转水平方向角度。示例代码:

    import turtle
    
    t = turtle.Turtle()
    screen = turtle.Screen()
    
    # 初始设置:朝东移动,全速
    t.setheading(0)
    t.speed(0)
    
    while True:
        x, y = t.pos()
        current_angle = t.heading()
    
        # 碰到左右边界,反转水平方向角度
        if x >= screen.window_width()/2 or x <= -screen.window_width()/2:
            t.setheading(180 - current_angle)
    
        # 碰到上下边界,反转垂直方向角度
        if y >= screen.window_height()/2 or y <= -screen.window_height()/2:
            t.setheading(360 - current_angle)
    
        t.forward(2)
    
  • 严格判断正朝东/西(适配浮点精度):
    如果需要精准判断海龟是否正朝东或西,可以用近似匹配处理角度的浮点误差:

    # 判断是否正朝东
    def is_facing_east(angle):
        normalized = angle % 360
        return abs(normalized) < 1 or abs(normalized - 360) < 1
    
    # 判断是否正朝西
    def is_facing_west(angle):
        normalized = angle % 360
        return abs(normalized - 180) < 1
    

内容的提问来源于stack exchange,提问作者aqwek_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 03:44:53