Superdimensional Pythons

Every so often, some deep seated instinct stirs within me, and I get the inexplicable urge to program a computer game. It never lasts for long, as my interests shift constantly, and projects I have no financial stake in rarely hold my attention for any substantial length of time. But my interests are cyclical, and so I make progress in increments, short bursts of activity before my curiosity wanes.

I’ll be posting some of the better snippets of code from the last time I had the compulsion to create a game. I had decided to create a Roguelike in Python, and so needed a set of functions to handle your classic Cartesian coordinate planes.

The grid function, which could be better named, constructs an n-dimensional set of pre-populated lists. So grid((3, 3)) will create a 3 x 3 structure, grid((4, 2, 3)) will create a 4 x 2 x 3 structure, and so forth.

def grid(size, item = None):
    def create(x, *xs):
        if xs: return [create(*xs) for i in xrange(x)]
        else:  return [item] * x
    return create(*size)

This function is an interesting one, because it uses variable length argument lists as a form of pattern matching, separating the head of a list from it’s tail without the need to resort to indices. Interestingly enough, this technique appears to be about 20% faster than using indices and slices, though it’s 50% slower than popping items off a disposable list.

The cross and xcross functions return the Cartesian product of their arguments:

def cross(*seqs):
    return list(xcross(*seqs))
 
def xcross(seq, *seqs):
    for x in seq:
        if seqs:
            for c in xcross(*seqs):
                yield (x,) + c
        else:
            yield (x,)

These two functions are rather useful when combined with the inbuilt range function.