Python Forum

Full Version: How to create a basic grid with functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm looking to create something like this

thisA function where I can draw a grid with an outline and specify the location of a body within the grid

for example in this image the function would read:

drawRoom(14,8,8,5)

the first two numbers being the grid dimensions and the last two being the location of the body.

I presume I would need three functions. One for +---+, one for line, ....., and one for the line with an object, ...@.

Any ideas?
You could do separate functions like you say, but I don't think you need to. You would print the top border, then loop through the rows of the grid. If it's the row with the @, print that, otherwise just print a row of dots. Then (after the loop) print the bottom border.
I had some spare time. How i´d do it.
def create_room(width, height, px, py):
    # fill room with dots
    room = [['.' for x in range(width+2)] for y in range(height+2)]
    # place horizontal '-'
    for i in range(width+2):
        room[0][i] = '-'
        room[height+1][i] = '-'
    # place vertical '|'
    for i in range(1, height+2):
        room[i][0] = '|'
        room[i][width+1] = '|'
    # place corners '+'
    for cy, cx in [(0, 0), (0, width+1), (height+1, 0), (height+1, width+1)]:
        room[cy][cx] = '+'
    # place player '@'
    room[py+1][px+1] = '@'
    return room

def draw(room):
    for y in range(len(room)):
        for x in range(len(room[0])):
            print(room[y][x], end='')
        print()

room = create_room(14, 8, 8, 5)
draw(room)