创建程序来随机化乌龟的移动,但不能让它从窗口/画布限制反弹。尝试了一些解决方案,提出了类似的问题,但仍然没有运气。
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()
答案 0 :(得分:1)
像
这样的东西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.
答案 1 :(得分:0)
这样的事情:
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
我猜你必须找出交叉点的位置。