Python 乌龟随机移动,从墙上反弹

Python 乌龟随机移动,从墙上反弹,python,python-3.x,turtle-graphics,Python,Python 3.x,Turtle Graphics,创建程序以随机化海龟的移动,但无法使其跳出窗口/画布限制。尝试了一些类似问题的解决方案,但仍然没有成功 from turtle import Turtle, Screen import random def createTurtle(color, width): tempName = Turtle("arrow") tempName.speed("fastest") tempName.color(color) tempName.width(width)

创建程序以随机化海龟的移动,但无法使其跳出窗口/画布限制。尝试了一些类似问题的解决方案,但仍然没有成功

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()
从海龟导入海龟,屏幕
随机输入
def createTurtle(颜色、宽度):
tempName=乌龟(“箭头”)
tempName.speed(“最快”)
tempName.color(颜色)
tempName.width(宽度)
返回临时名称
def屏幕(屏幕、turt):
x=屏幕。窗口高度()/2
y=屏幕。窗口高度()/2
最小值x,最大值x=-x,x
最小值,最大值=-y,y
turtleX,turtleY=turt.pos()
而(min_x类似这样的东西:

while true:
    if (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)
    else:
# Put code here to move the turtle to where it intersected the edge
# and then bounce off
为true时:
如果(min_x类似

old_position = turtle.position()  # Assume we're good here.
turtle.move_somehow()  # Turtle computes its new position.
turtle_x, turtle_y = turtle.position()  # Maybe we're off the canvas now.
if not (min_x <= turtle_x <= max_x) or not (min_y <= turtle_y <= max_y):
   turtle.goto(*old_position)  # Back to safely.
   turtle.setheading(180 - turtle.heading())  # Reflect.
old_position=turtle.position()#假设我们在这里很好。
海龟。以某种方式移动()#海龟计算其新位置。
海龟x,海龟y=tutle.position()#也许我们现在离开了画布。

如果不是(min_x预期会发生什么,你会得到什么?为什么你认为这会被破坏?@Andreiciara根据当前代码,海龟会随机移动,直到撞到墙上。然后循环停止,当我点击窗户时,它就会关闭。我试着让它撞到墙上时,它会以随机方向反弹,并继续移动,直到被强行关闭。看起来It’好像当你的乌龟越界时你正在退出循环。也许你应该永远留在循环中,用一个if语句修改你越界时的位置和方向?@BobbyDurrett类似这样的话?`而True:turt.left(random.randrange(360))turt.fd(random.randrange(50))turtleX,turtleY=turt.pos()打印(turtleX,,,,turtleY)如果(min_x>=turtleX>=max_x)和(min_y>=turtleY>=max_y):turt.setheading(90)turtleX,turtleY=turt.pos()`我投票结束话题,因为这里没有问题(而且隐含的“我写什么代码?”太宽泛了).好的,这是可行的!但是有没有一种方法可以中途停止或中断当前路线,并进行反思?因为当前,假设乌龟处于边缘,它离开屏幕100个单位,然后返回。可能有一种方法可以在100个单位之前停止或切断它?或者你将下一个动作委托给乌龟,或者你不委托。如果你委托,你应该检测到乌龟被禁止进入,并修复它。如果你没有,你应该自己独立地、正确地计算新的坐标,并将可能的移动分割成多个部分(如果靠近矩形的一角,可能是3个;递归有帮助),然后沿着你计算的反射线征用乌龟。