使用Python绘制/绘制类似迷宫的线条?

时间:2018-07-23 22:34:45

标签: python plot draw lines

编程新手,我试图绘制类似于道路边界的线。基本上,我正在创建路线图之类的东西,我希望矩形始终沿轨迹移动(我的意思是,矩形的x,y坐标相对于直线增加)。

这个想法就像下面的图片。

有人可以帮助我吗?如何创建和绘制沿箭头方向移动的红线和黑矩形?

更新:我需要每次检查从矩形到线条的距离是否在某个阈值以下。我想我可能需要使用某种数组/元素。但是我不清楚如何使用它。谁能帮我?谢谢。

the figure

2 个答案:

答案 0 :(得分:0)

您可以使用pygames并从字面上绘制任何内容。由于您还没有开始使用它,因此请尝试本教程here

或者您可以尝试turtle.

答案 1 :(得分:0)

  

或者您可以尝试乌龟。

下面是我在Python turtle中实现的极简地图关注者。 (不是迷宫追随者,因为它不会进行任何回溯。)这应该使您大致了解如何绘制迷宫和使用数组包含迷宫结构的对象在迷宫中移动的情况:

from turtle import Turtle, Screen

MAP = '''
XXXXXXXXOX
XOOOOOOOOX
XOXXXXXXXX
XOOOOXXXXX
XXXXOXXXXX
XXXXOXXXXX
XXXXOOOOOX
XXXXXXXXOX
XOOOOOOOOX
XOXXXXXXXX
'''

MAP_ARRAY = [list(row) for row in MAP.strip().split('\n')]
MAP_ARRAY.reverse()  # put 0, 0 in lower left corner

ADJACENT = [
              (0,  1),
    (-1,  0),          (1,  0),
              (0, -1),
]

SCALE = 3

STAMP_SIZE = 20

WIDTH, HEIGHT = len(MAP_ARRAY[0]), len(MAP_ARRAY)

def any_adjacent(x, y):
    return [(x + dx, y + dy) for dx, dy in ADJACENT if 0 <= x + dx < WIDTH and 0 <= y + dy < HEIGHT and MAP_ARRAY[y + dy][x + dx] == 'O']

def move():  # slowly navigate the MAP, quit when no where new to go
    x, y = turtle.position()
    adjacent_squares = any_adjacent(int(x), int(y))

    # always moves to first valid adjacent square, need to consider
    # how to deal with forks in the road (e.g. shuffle adjacent_squares)
    for adjacent in adjacent_squares:
        if adjacent not in been_there:
            turtle.goto(adjacent)
            been_there.append(adjacent)
            screen.ontimer(move, 1000)  # one second per move, adjust as needed
            break

screen = Screen()  # recast the screen into MAP coordinates
screen.setup(WIDTH * STAMP_SIZE * SCALE, HEIGHT * STAMP_SIZE * SCALE)
screen.setworldcoordinates(-0.5, -0.5, WIDTH - 0.5, HEIGHT - 0.5)

turtle = Turtle('square', visible=False)
turtle.shapesize(SCALE)
turtle.speed('fastest')
turtle.penup()

for y, row in enumerate(MAP_ARRAY):  # draw the MAP
    for x, character in enumerate(row):
        if character == 'X':
            turtle.goto(x, y)
            turtle.stamp()

turtle.color('red')
turtle.shapesize(SCALE / 2)
turtle.goto(1, 0)  # should use unique character in MAP to indicate start & end points
turtle.showturtle()

been_there = []  # prevent doubling back

move()

screen.mainloop()

enter image description here