Search code examples
pythonlisttileisometric

Need a clever way to create a large list for a pygame/pyOpenGL project


Basically I need lists of rows that go like this:

[0,0]

[1,0],[0,1]

[2,0],[1,1],[0,2]

[3,0],[2,1],[1,2],[0,3]

[4,0],[3,1],[2,2],[1,3],[0,4]

up to an arbitrary number of elements and then back down

[4,1],[3,2],[2,3],[1,4]

[4,2],[3,3],[2,4]

[4,3],[3,4]

[4,4]

I'm just wanting all of these pairs in one large list of lists, so I can iterate over the pairs in the order they appear above for isometric rendering.

the output would look like this

[ [ (0,0) ], [ (1,0),(0,1) ], [ (2,0), (1,1), (0,2) ]....]etc


Solution

  • It's not entirely clear what generalization you're looking for, but IIUC there are lots of ways you can do it. One is to build each sublist from the previous list (adding one to each subelement and avoiding duplicates), but another is to work directly from the arithmetic:

    def sherwood(n):
        N = 2*n+1
        for i in range(N):
            low, high = max(0, i-n), min(i, n)
            w = list(range(low, high+1))
            yield zip(w[::-1], w)
    

    gives me

    >>> out = list(sherwood(2))
    >>> for x in out: print(x)
    [(0, 0)]
    [(1, 0), (0, 1)]
    [(2, 0), (1, 1), (0, 2)]
    [(2, 1), (1, 2)]
    [(2, 2)]
    >>> out = list(sherwood(4))
    >>> for x in out: print(x)
    [(0, 0)]
    [(1, 0), (0, 1)]
    [(2, 0), (1, 1), (0, 2)]
    [(3, 0), (2, 1), (1, 2), (0, 3)]
    [(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]
    [(4, 1), (3, 2), (2, 3), (1, 4)]
    [(4, 2), (3, 3), (2, 4)]
    [(4, 3), (3, 4)]
    [(4, 4)]