乌龟的无限循环听

时间:2017-03-04 21:17:48

标签: python-3.x turtle-graphics

我在这段代码中遇到了无限循环。如果你点击所需的范围,它应该会爆发,但它会进入一个无限循环,以行和列的形式显示乌龟的当前位置。

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)

1 个答案:

答案 0 :(得分:0)

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

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] - 你可能想做一些数学运算来切换它们。