Python:如何让乌龟永远不会越过一条线

时间:2017-02-08 18:39:31

标签: python turtle-graphics

我试图编写一个python程序,让乌龟向前移动,向左转,然后移动,或向右转,然后随机移动而不会越过自己先前绘制的线。它必须保持在屏幕内,并在完成最可能的移动后清除并重新启动。这是我得到的:

{{1}}

如何让它记住它的位置而不是重复它们?非常感谢!

1 个答案:

答案 0 :(得分:1)

以下是我尝试解决您的自治龟问题。我选择set()来跟踪访问过的位置,但也将乌龟强制到网格上,以确保只能访问一组有限的点。当你撞墙时,我不喜欢你做180的做法,只是让你回到自己的路上而失败 - 而是我的乌龟试图避免撞到墙壁。

我使用一只看不见的乌龟克隆来“测试水域”,看看一次移动是好还是坏。如果没有好的动作,它会放弃,重置并重新开始。你必须关闭窗口才能杀死该程序:

import turtle
from random import shuffle

WIDTH, HEIGHT = 600, 500

INCREMENT = 50

TURTLE_WIDTH = 20

X, Y = 0, 1

def dot_round(x, base=INCREMENT):
    return int(base * round(float(x) / base))

turtle.setup(WIDTH, HEIGHT)

turtle.shape("turtle")

while True:
    positions = set()

    while True:

        position = (dot_round(turtle.xcor()), dot_round(turtle.ycor()))  # coerce position to grid

        if position in positions:
            break  # collision with line

        positions.add(position)

        turtle.setposition(position)  # coerce turtle back onto our grid

        moves = list(range(3))

        shuffle(moves)

        clone = None

        for move in moves:
            clone = turtle.clone()  # use an invisible clone to test the waters
            clone.hideturtle()
            clone.penup()

            if move == 1:
                clone.right(90)
            elif move == 2:
                clone.left(90)

            clone.forward(INCREMENT)

            position = (dot_round(clone.xcor()), dot_round(clone.ycor()))

            if position[X] <= TURTLE_WIDTH//2 - WIDTH//2 or position[X] > WIDTH//2 - TURTLE_WIDTH//2:
                continue  # avoid collision with wall

            if position[Y] <= TURTLE_WIDTH//2 - HEIGHT//2 or position[Y] > HEIGHT//2 - TURTLE_WIDTH//2:
                continue  # avoid collision with wall

            if position not in positions:
                break

        else:  # no break
            break  # accept the inevitable, there's no good move

        turtle.setheading(clone.heading())
        turtle.forward(INCREMENT)

    turtle.reset()

# close the turtle window to get out of this program

这只乌龟看起来只有前进一步 - 他很容易陷入陷阱,他无法让自己离开。

enter image description here

这有希望为您提供一些如何设计自己的乌龟自动机的建议。