【发布时间】:2018-03-21 22:25:18
【问题描述】:
创建了程序来随机化海龟的移动,但不能让它从窗口/画布限制反弹。尝试了一些发布类似问题的解决方案,但仍然没有成功。
from turtle import Turtle, Screen
import random
def createTurtle(color, width):
tempName = Turtle("arrow")
tempName.speed("fastest")
tempName.color(color)
tempName.width(width)
return tempName
def inScreen(screen, turt):
x = screen.window_height() / 2
y = screen.window_height() / 2
min_x, max_x = -x, x
min_y, max_y = -y, y
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(50))
turtleX, turtleY = turt.pos()
print(turtleX, ",", turtleY)
wn = Screen()
alpha = createTurtle("red", 3)
inScreen(wn, alpha)
wn.exitonclick()
【问题讨论】:
-
期待什么,你会得到什么?为什么你认为这是坏的?
-
@AndreiCioara 使用当前代码,海龟会随机移动,直到撞到墙上。之后循环停止,当我单击窗口时它会关闭。我正在尝试让它在撞到墙壁时向随机方向弹跳并继续直到被强制关闭。
-
当您的海龟越界时,您似乎正在退出循环。也许你应该永远留在你的循环中,并有一个 if 语句来修改你会越界时的位置和方向?
-
@BobbyDurrett 是这样的吗? ` while True: turt.left(random.randrange(360)) turt.fd(random.randrange(50)) turtleX, turtleY = turt.pos() print(turtleX, ",", turtleY) if (min_x >= turtleX >= max_x) 和 (min_y >= turtleY >= max_y): turt.setheading(90) turtleX, turtleY = turt.pos()`
-
我投票决定作为题外话结束,因为这里没有问题(而且暗示的“我要写什么代码?”太宽泛了)。
标签: python python-3.x turtle-graphics