gpt4 book ai didi

python - turtle 随机运动,从墙上弹起

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:40 24 4
gpt4 key购买 nike

创建了程序来随机化 turtle 的移动,但无法让它弹离窗口/ 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()

最佳答案

类似于

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.

关于python - turtle 随机运动,从墙上弹起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49417524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com