【问题标题】:Random Turtle movement, bound in window随机海龟运动,绑定在窗口中
【发布时间】:2018-03-21 19:19:56
【问题描述】:

创建了程序来随机化海龟的运动,但一旦它接触到边界(窗口)就不能让它打破循环。尝试了一些发布类似问题的解决方案,但仍然没有成功。

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()

【问题讨论】:

  • 您需要在while 循环内更新turtleX, turtleY = turt.pos()
  • @JohnnyMopp 啊,这是有道理的......不更新它总是指(0,0)。谢谢!

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


【解决方案1】:

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

这就是为什么你的打印函数只输出0.0 , 0.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 2020-06-17
    • 2022-06-23
    • 2018-11-03
    相关资源
    最近更新 更多