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

Python Turtle赛车代码运行无响应,请求排查错误

问题排查与修复

你的程序出现“Python停止响应”是因为缩进错误导致的死循环,核心问题在于乌龟前进的代码被错误地放在了else块中,只有当用户赌输时才会执行移动,大部分情况下乌龟根本不会前进,比赛永远无法结束,while循环一直占用CPU资源导致程序假死。

错误代码的问题点

看这段关键代码:

while race_on:
    for turtle in new_tur:
        if turtle.xcor()>230:
                race_on=False
                winning_tur=turtle.pencolor()
                if winning_tur==user_bet:
                    print(f"You've won {winning_tur} is the winner")
                else:
                    print(f"You've lost {winning_tur} is the winner")
                    turtle.forward(random.randint(0,10))
  • turtle.forward(...)被缩进在else块内,只有当用户赌输时才会让乌龟移动,而如果用户赌对或者乌龟还没到终点,乌龟完全不动,比赛永远无法结束,while循环持续运行导致程序无响应。
  • 当检测到有乌龟冲线后,没有及时终止for循环,可能会让后续乌龟也触发冲线判断,导致结果混乱。

修正后的代码

import random
from turtle import Turtle, Screen

screen = Screen()
screen.setup(width=500, height=400)   # 设置屏幕尺寸
race_on = False

# 获取用户赌注
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color:")
print(user_bet)

# 乌龟颜色列表
color = ["red", "green", "yellow", "blue", "orange", "purple"]
# 初始Y轴位置
y_position = [-100, -60, -20, 20, 60, 100]
new_tur = []

# 创建并定位所有乌龟
for i in range(6):
    tur = Turtle()
    tur.shape("turtle")
    tur.color(color[i])
    tur.penup()
    tur.goto(x=-230, y=y_position[i])
    new_tur.append(tur)

if user_bet:
    race_on = True

while race_on:
    for turtle in new_tur:
        # 只要比赛还在进行,就让乌龟随机前进
        turtle.forward(random.randint(0, 10))
        
        # 检测是否冲线
        if turtle.xcor() > 230:
            race_on = False
            winning_tur = turtle.pencolor()
            if winning_tur == user_bet:
                print(f"You've won! {winning_tur} is the winner")
            else:
                print(f"You've lost! {winning_tur} is the winner")
            # 跳出for循环,不再处理其他乌龟
            break

screen.exitonclick()

修正说明

  1. 调整前进代码的缩进:把turtle.forward(random.randint(0,10))移到if判断外面,确保每一轮循环中所有乌龟都会随机前进,比赛能正常推进到终点。
  2. 添加break终止for循环:当检测到有乌龟冲线后,立即跳出for循环,避免后续乌龟继续移动,保证只判定第一个到达终点的乌龟为胜者。
  3. 修正提示文本的拼写错误:原代码中的whicht改为Which,wint改为win,让提示更准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:31:01