[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Storing images in a list



Thank you, Jake and Charlie. I appreciate your responses. I don't think I have to change anything. The concern was storing explicit copies in the list versus pointing. All clear now. Storing 360 elements of red stone is the same as 5 so long as I load it only once. That's what I hoped and I'm glad that's how it is.

Jake b wrote:
Like Charlie said: as long as you make sure you only have one call per
unique filename, then you will not have copies.

But you can make it easier on yourself, by writing a basic
texture/surface manager so that repeated calls only load the surface
once.

( If you don't want to use an id, you can remove that, and use
filename as the key. )

Source:
	
class TextureManager:
	"""a very basic texture manager
	
	members:
		tex_list : a dict() using (k,v) pairs as ( id, pygame.Surface() )"""
	def __init__(self):
		self.tex_list = {}
		
	def load_image(self, id, filename):
		"""Loads image and returns it.
		Doesn't load redundant images for same key."""
		# don't load if already loaded
		if not id in self.tex_list:
			self.tex_list[id] = pygame.image.load(filename).convert_alpha ()
			print "created new image for: %s" % id
		return self.tex_list[id]
		
Usage: ( output from IDLE ):
	
t = TextureManager()
t.load_image("red", "red.png")
created new image for: red
<Surface(10x10x32 SW)>
t.load_image("red", "red.png")
<Surface(10x10x32 SW)>