Skip to content Skip to sidebar Skip to footer

Plot /draw Maze-like Lines With Python?

New to programming, I am trying to plot road boundary-like lines. Basically, I am creating something like a road map and I want a rectangle to always be moving through the trajecto

Solution 1:

You can use pygames and literally draw anything anyway. Since you have not started on it at all, try this tutorial here

Or you could try turtle.

Solution 2:

Or you could try turtle.

Below's a minimalist map follower I implemented in Python turtle. (Not a maze follower as it doesn't do any backtracking.) This should give you a rough idea how to plot a maze and an object moving through it using an array to contain the maze structure:

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)

defany_adjacent(x, y):
    return [(x + dx, y + dy) for dx, dy in ADJACENT if0 <= x + dx < WIDTH and0 <= y + dy < HEIGHT and MAP_ARRAY[y + dy][x + dx] == 'O']

defmove():  # 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 notin been_there:
            turtle.goto(adjacent)
            been_there.append(adjacent)
            screen.ontimer(move, 1000)  # one second per move, adjust as neededbreak

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 inenumerate(MAP_ARRAY):  # draw the MAPfor x, character inenumerate(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

Post a Comment for "Plot /draw Maze-like Lines With Python?"