【问题标题】:Random Turtle movement, bounce off wall海龟随机运动,从墙上反弹
【发布时间】:2018-03-21 22:25:18
【问题描述】:

创建了程序来随机化海龟的移动,但不能让它从窗口/画布限制反弹。尝试了一些发布类似问题的解决方案,但仍然没有成功。

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

【问题讨论】:

  • 期待什么,你会得到什么?为什么你认为这是坏的?
  • @AndreiCioara 使用当前代码,海龟会随机移动,直到撞到墙上。之后循环停止,当我单击窗口时它会关闭。我正在尝试让它在撞到墙壁时向随机方向弹跳并继续直到被强制关闭。
  • 当您的海龟越界时,您似乎正在退出循环。也许你应该永远留在你的循环中,并有一个 if 语句来修改你会越界时的位置和方向?
  • @BobbyDurrett 是这样的吗? ` while True: turt.left(random.randrange(360)) turt.fd(random.randrange(50)) turtleX, turtleY = turt.pos() print(turtleX, ",", turtleY) if (min_x >= turtleX >= max_x) 和 (min_y >= turtleY >= max_y): turt.setheading(90) turtleX, turtleY = turt.pos()`
  • 我投票决定作为题外话结束,因为这里没有问题(而且暗示的“我要写什么代码?”太宽泛了)。

标签: python python-3.x turtle-graphics


【解决方案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.

【讨论】:

  • 好的,行得通!但是有没有办法中途停止或打破当前的路线并进行反思?因为目前,假设海龟处于边缘,它会离开屏幕 100 个单位然后返回。也许有一种方法可以在全部 100 个单位之前停止或切断它?
  • 要么将下一个动作委托给海龟,要么不委托。如果您委托,您应该检测到海龟超出限制,并修复它。如果不这样做,您应该自己独立且正确地计算新坐标,并将可能的移动分割成多个段(如果靠近矩形的角可能是 3 个;递归有帮助),然后征用海龟沿着你计算的反射线。
【解决方案2】:

类似这样的:

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

我猜你必须弄清楚交点在哪里。

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多