2017-03-04 4 views
0

このコードでは無限ループに陥っています。あなたが望む範囲をクリックすると壊れますが、行と列の形式でカメの現在の位置を表示する無限ループに入ります。タートルのための無限ループ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) 

答えて

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]です。これらを切り替えるには数学を行うとよいでしょう。