乌龟随机移动,邦恩

2024-09-28 22:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

创建了一个程序来随机化乌龟的移动,但无法使其反弹到窗口/画布的限制。尝试了一些类似的问题,但仍然没有运气。在

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

Tags: importdefrandomminwidthscreenmaxcolor
2条回答

有点像

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.

像这样:

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

我想你得找出交叉点在哪里。在

相关问题 更多 >