随机海龟移动,绑定 window
Random Turtle movement, bound in window
创建了使乌龟移动随机化的程序,但无法让它在触及边界后打破循环 (window)。尝试了一些类似问题的解决方案,但仍然没有成功。
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,但您从未在循环中重新计算它们。
这就是为什么你的打印函数只输出 0.0 , 0.0
创建了使乌龟移动随机化的程序,但无法让它在触及边界后打破循环 (window)。尝试了一些类似问题的解决方案,但仍然没有成功。
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,但您从未在循环中重新计算它们。
这就是为什么你的打印函数只输出 0.0 , 0.0