随机龟运动,在窗口中绑定

时间:2018-03-21 19:19:57

标签: python python-3.x turtle-graphics

创建程序来随机化乌龟的移动,但是一旦接触到边界(窗口)就无法让它破坏循环。尝试了一些解决方案,提出了类似的问题,但仍然没有运气。

from turtle import Turtle, Screen
import random

def createTurtle(color, width):
    tempName = Turtle("turtle")
    tempName.speed("fastest")
    tempName.color(color)
    tempName.width(width)
    return tempName

def inScreen(screen, turt):

    min_x, max_x = -wn.window_width() / 2 , wn.window_width() / 2
    min_y, max_y = -wn.window_height() / 2 , wn.window_height() / 2

    turtleX, turtleY = turt.pos()

    while (min_x < turtleX < max_x) and (min_y < turtleY < max_y):
        turt.left(random.randrange(360))
        turt.fd(random.randrange(100))
        turtleX, turtleY = turt.pos()
        print(turtleX, ",", turtleY)


wn = Screen()

alpha = createTurtle("red", 3)

inScreen(wn, alpha)

wn.exitonclick()

1 个答案:

答案 0 :(得分:0)

变量turtleX和turtleY正在您的while条件中使用,但您永远不会在循环中重新评估它们。

这就是您的打印功能仅输出0.0 , 0.0

的原因