乌龟在 While 循环中崩溃

Turtle Crashing In While Loop

当我在下面的脚本中初始化 Turtle 时,它​​总是挂起。 我正在使用 Python IDLE 3.9.0a3。我已尝试将 IDLE 配置添加到 turtle.cfg,但无济于事。 我使用的代码是:

from turtle import *
speed(0)

while True:
    penup()
    home()
    setheading(0)
    num = int(input('Number to check?'))
    ang = int(input('Angle to turn?'))
    pendown()
    print(num)
    while True:
        if num % 2 == 0:
            num = num // 2
            print(num)
            right(ang)
        if num == 1:
            break
        if num % 2 != 0:
            num = num * 3
            num = num + 1
            print(num)
            left(ang)

我在您的代码中更改了一些内容,但它似乎在我的机器上运行正常

  1. 我添加了 forward() 以确保笔实际移动得更远而不仅仅是转动。 10 是一个距离度量,你可以玩弄它。
  2. 我添加了exitonclick()功能,确保当你点击它时乌龟屏幕会关闭

请注意,出于测试目的,此处删除了外部 while 循环,但您可以很容易地将其添加回去。

from turtle import *
speed(0)

penup()
home()
setheading(0)
num = int(input('Number to check?'))
ang = int(input('Angle to turn?'))
pendown()
print(num)
while True:
    if num % 2 == 0:
        num = num // 2
        print(num)
        right(ang)
        forward(10)
    elif num == 1:
        break
    else:
        num = num * 3
        num = num + 1
        print(num)
        left(ang)
        forward(10)
exitonclick()

the whole idea is that it overlaps and creates interesting patterns, not just creating a single line. It kind of needs to be in a loop for this to happen ... I tried this, and Turtle still hangs...

让我们试试不同的方法。首先,我们将抛出有问题的 while True: 语句。接下来,我们会将用户输入视为一个限制,因此我们将执行所有行直到该数字。我们将使用计时器事件来启动每个手臂并允许事件在两者之间 运行,而不是可能导致 OS 问题的非阻塞紧密循环:

from turtle import *

limit = int(input('Limit of check?'))
angle = int(input('Angle to turn?'))

hideturtle()
tracer(False)

candidate = 1

def draw():
    global candidate

    if candidate < limit:

        number = candidate
        pendown()

        while number != 1:

            if number % 2 == 0:
                number //= 2
                right(angle)
                forward(10)
            else:
                number = number * 3 + 1
                left(angle)
                forward(10)

        update()
        penup()
        home()

        candidate += 1
        ontimer(draw, 25)  # milliseconds

draw()

exitonclick()

看看这个 运行 是否更适合您。下一个增强可能是使用 turtle 的 numinput(...) 而不是 int(input(...)).