Grid Utility

The Grid class in grid.py provides a simple 2-d storage utility. The values stored can be any Python value.

Grid(width, height) - constructs new grid. Initially all locations are None

grid.width, grid.height - width/height properties

grid.get(x, y) - returns contents at x,y

grid.set(x, y, val) - sets value into the grid at x,y

grid.in_bounds(x, y) - returns True if the x,y is in bounds of the grid. False otherwise.

build(lst) - constructs a new grid based on a nested-list format like this

# e.g. this makes a 3 by 2 grid:
grid = Grid.build([[1, 2, 3], [4, 5 6]])
# [1, 2, 3] is row y = 0
# [4, 5, 6] is row y = 1

Grid Demo

def grid_demo():
    """
    Demonstrate use of the Grid class.
    """
    # Create width 4 by height 2 grid, filled with None initially.
    grid = Grid(4, 2)

    # loop over contents in usual way,
    # setting every location to 6
    for y in range(grid.height):
        for x in range(grid.width):
            grid.set(x, y, 6)


    # access 0,0
    val = grid.get(0, 0)

    # verify that 3,1 is in bounds
    if grid.in_bounds(3, 1):
        # set 3,1
        grid.set(3, 1, 11)

    print(grid)
    # print uses nested-list format
    # showing row-0, then row-1
    # [[6, 6, 6, 6], [6, 6, 6, 11]]

    # Grid.build() also uses nested-list format, allowing
    # you to construct a grid on the fly.
    grid2 = Grid.build([[6, 6, 6, 6], [6, 6, 6, 11]])