有没有办法逆转的运动

is there a way to reverse a turtle movement

提问人:Oliver Parr 提问时间:11/7/2023 更新时间:11/8/2023 访问量:47

问:

所以我得到了一些代码,使它朝着一个随机的方向发展,我希望它有边框

nextpos = [
        (turtle.xcor() + 50, turtle.ycor()),
        (turtle.xcor() - 50, turtle.ycor()),
        (turtle.xcor(), turtle.ycor() + 50),
        (turtle.xcor(), turtle.ycor() - 50)
    ]
    rnextpos = random.randint(0,3)
    turtle.goto(nextpos[rnextpos])

这是代码,我的想法就是拥有这个

nextpos = [
        (turtle.xcor() - 50, turtle.ycor()),
        (turtle.xcor() + 50, turtle.ycor()),
        (turtle.xcor(), turtle.ycor() - 50),
        (turtle.xcor(), turtle.ycor() + 50)
    ]
    turtle.goto(nextpos[rnextpos])

但它似乎不起作用,不知道为什么 有什么想法吗?

蟒蛇 python-turtle python-3.11

评论

2赞 JonSG 11/7/2023
给定先前的移动,您是想撤消它,还是要跟踪所有移动以撤消多个移动?
0赞 Oliver Parr 11/7/2023
只需 1 步,谢谢
1赞 ggorlen 11/8/2023
你试过撤消吗?您能否为正在创建的应用程序提供上下文?“不工作”究竟意味着什么?感谢您的澄清。
0赞 JonSG 11/9/2023
如果 OP 想要有效地擦除先前的线绘制,@ggorlen是完美的。很棒的推荐!undo()
0赞 ggorlen 11/9/2023
没关系。可能与此相关:如何通过按键撤消 python turtle 模块中的某些内容?

答:

0赞 JonSG 11/8/2023 #1

您应该能够通过将当前位置设置为变量来跟踪当前位置。然后,您可以使用代码计算新的位置变量。具有新位置的 goto 可以通过 goto 当前位置来反转。

这应该去,然后撤消很多次。

import turtle
import random
import time

def get_random_move(current_position, distance=50):
    next_position = list(current_position)
    index = random.choice([0,1]) ## x or y
    dist = random.choice([distance, -distance]) ## plus or minus
    next_position[index] += dist
    return next_position

for _ in range(10):
    current_position = turtle.pos()
    next_position = get_random_move(current_position)

    time.sleep(0.5)
    turtle.goto(next_position)
    time.sleep(0.5)
    turtle.goto(current_position)