乌龟听的无限循环

Infinite loops for turtle listen

我运行进入了这段代码的死循环。如果您在所需范围内单击,它应该会断开,但它会进入无限循环,以行和列格式显示乌龟的当前位置。

def wait_for_click():
    turt.penup()
    wn.onclick(turt.goto)
    wn.listen()
    pos = [-1,-1]
    row = -1
    column = -1
    while row > 8 or row < 0  or column > 8 or column < 0:
        row = ((turt.ycor()-turt.ycor()%75)+75)/75 + 4
        column = ((turt.xcor()-turt.xcor()%75)+75)/75 + 4
    pos[0] = row
    pos[1] = column
    print(pos)

我认为你的基本方法是错误的:不要循环等待海龟出现在某个有趣的地方,而是使用点击处理程序来测试海龟出现的位置:

from math import ceil
from turtle import Turtle, Screen

CELLS = 8
CELL_SIZE = 75
STAMP_SIZE = 20

def click_handler(x, y):
    screen.onclick(None)

    yertle.goto(x, y)

    if 0 < x < CELLS and 0 < y < CELLS:
        position = [ceil(x), ceil(y)]
        print(position)

    screen.onclick(click_handler)

screen = Screen()
screen.setup(CELL_SIZE * (CELLS + 2), CELL_SIZE * (CELLS + 2))
screen.setworldcoordinates(-1, -1, CELLS + 1, CELLS + 1)

screen.onclick(click_handler)

marker = Turtle(shape="square")
marker.penup()
marker.turtlesize(CELL_SIZE / STAMP_SIZE)
marker.color("gray", "white")

for x in range(0, CELLS):
    for y in range(0, CELLS):
        marker.goto(x + 0.5, y + 0.5)
        marker.stamp()
        marker.color(*marker.color()[::-1])
    marker.color(*marker.color()[::-1])

yertle = Turtle(shape="circle")
yertle.speed("fastest")
yertle.penup()

screen.mainloop()

我添加了代码来显示网格,这样您就可以看到您点击的位置与打印输出相匹配。我使用 setworldcoordinates() 来简化问题,因为我给了你一个更大的边框。

左下角的单元格是 [1, 1],右上角的单元格是 [8, 8] -- 您可能需要做一些数学运算来调换它们。