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

Python使用turtle模块开发乌龟赛跑游戏时乌龟静止无响应问题

Turtle赛跑游戏不动问题修复方案

核心问题点

  • 初始坐标超出可视区:你设置的画布宽度为500,x轴可视范围为-250~250,但左右两只乌龟初始x坐标设为-300和300,直接在画布外,无法观察到移动。
  • 移动逻辑顺序错误:当前代码是先让第一只乌龟跑完全程,再启动第二只、第三只,不是同时赛跑的效果。
  • 终止条件存在死循环风险:用ycor() != 250作为终止判断,一旦因为浮点数精度问题跳过250这个值,乌龟会无限向上移动,永不停止。
  • 缺少窗口保持逻辑:代码执行完移动逻辑后会直接退出,可能来不及观察到移动过程窗口就关闭了。

修正后可运行代码

import turtle
import random

Bank_account = 0

class turtle_s:
    def __init__(self, color):
        self.color = color
        self.turt = turtle.Pen()
        self.turt.shape('turtle')
        self.turt.color(color)

red_turtle = turtle_s('red')
blue_turtle = turtle_s('blue')
yellow_turtle = turtle_s('yellow')

turtle_list = [red_turtle, blue_turtle, yellow_turtle]

## Turtle Game Setup
def turtle_stuff():
    turtle.screensize(canvwidth=500, canvheight=500)
    turtle.bgcolor('black')
    # 调整x坐标在可视范围内
    pos_x = [-200, 0, 200]
    for idx, color_turtle in enumerate(turtle_list):
        color_turtle.turt.penup()
        color_turtle.turt.setpos(pos_x[idx], -250)
        color_turtle.turt.left(90)
        color_turtle.turt.speed(random.randint(3,5))

def turtle_move():
    # 把while循环放到外面,每次循环三只乌龟各走一步,实现同时跑的效果
    while True:
        all_arrived = True
        for color_turtle in turtle_list:
            if color_turtle.turt.ycor() < 250:
                all_arrived = False
                color_turtle.turt.forward(5)
        if all_arrived:
            break

turtle_stuff()
turtle_move()
turtle.done()

修改说明

  • 调整了三只乌龟的初始x坐标为-200、0、200,全部在画布可视区域内
  • 重构了移动逻辑,每次循环三只乌龟各移动一步,实现同时赛跑的效果
  • 把终止条件改为ycor() < 250,避免死循环
  • 新增 turtle.done()保持窗口显示,直到手动关闭
  • 优化了初始位置赋值逻辑,用enumerate代替index判断,运行效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:27:03