Sprite tile grabber

I’m remaking an old game from the mid 1990 in which I’m using the origional graphic assets. Many games at the time put many sprites in a single image. Like OpenTTD I’m unable to redistribute the origional assets due to copyright laws. I decided to make a more universal function for people who may also want to do something similar. This function will return your desired sprite image, with transparency.

Many thanks to ZeroByte and ThomasEgi for their help in IRC

from pandac.PandaModules import PNMImage, Filename, Texture, VBase4D

def Tile(sourceImgPath = '', alphaColor = (None, None, None), tileSize = (0, 0), location = (0,0)):
	'''
	Generates a "tile" (image) from a sprite-table-like image file. Returns PNMImage
	sourceImgPath: string path to image
	alphaColor: (1, 1, 1) A tuple of RGB values that should be transparent.  None for values that should be ignored
	tileSize: A (x, y) tuple for the tile size used in the source image
	location:	A (x, y) tuple for the top left corner of the tile in the source image
	'''
	tiles = PNMImage()
	textureFile = Filename(sourceImgPath)
	tiles.read(textureFile)
	tile = PNMImage(tileSize[0], tileSize[1])
	tile.copySubImage(tiles, 0, 0, location[0], location[1])
	tile.addAlpha()
	tile.alphaFill(1)	
	# This is terrable, ugly, horrible mess
	for xi in range(tile.getXSize()):
		for yi in range(tile.getYSize()):
			matchPattern = []
			for i in range(len(alphaColor)):
				if alphaColor[i]:
					matchPattern.append( alphaColor[i])
				else:
					matchPattern[i] = self.tile.getXelA(xi,yi)[i]
			matcher =  VBase4D(matchPattern[0], matchPattern[1], matchPattern[2], 1)
			if tile.getXelA(xi,yi) == matcher:
				tile.setAlpha(xi,yi,0)
				
	return tile

neat. Also vgmaps.com/Atlas/NES/index.htm is great to get the feel for levels of old games.