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

问题描述 投票:0回答:2

编程新手,我试图绘制道路边界线。基本上,我正在创建类似路线图的东西,我想要一个矩形总是在轨迹中移动(我的意思是,矩形的x,y坐标相对于线条增加)。

这个想法就像下图。

谁能帮我?如何创建和绘制红线以及沿箭头方向移动的黑色矩形?

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

the figure

python plot draw lines
2个回答
0
投票

无论如何,你可以使用pygames并逐字绘制。由于您还没有开始使用它,请尝试本教程here

或者你可以试试turtle.


0
投票

或者你可以试试乌龟。

下面是我在Python龟中实现的极简地图追随者。 (不是迷宫追随者,因为它不会进行任何回溯。)这应该让您大致了解如何使用数组来绘制迷宫和穿过它的物体以包含迷宫结构:

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

© www.soinside.com 2019 - 2024. All rights reserved.