随机海龟运动,从墙上反弹

Random Turtle movement, bounce off wall

创建了使海龟运动随机化的程序,但无法让它弹开 window/canvas 限制。尝试了一些类似问题的解决方案,但仍然没有成功。

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

像这样:

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

我猜你得弄清楚交点在哪里

类似

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.