OMG please help

Martin P. Hellwig xng at xs4all.nl
Mon Dec 24 11:14:58 EST 2007


Steven D'Aprano wrote:
> Hi Katie,
> 
> Please try to write more descriptive subject lines. "OMG please help" 
> makes you sound like a 14 y.o. breathless school girl who has just broken 
> a nail. Probably 3/4th of the regulars who *could* help haven't even read 
> your post because of the subject line.
> 
> On Sat, 22 Dec 2007 15:16:53 -0800, katie smith wrote:
> 
>> Here is the program I just started, The problem i am having is I'm
>> trying to get it to load the image file Sand1 with eval(loader) =
>> pygame.image.load(loader) because Loader is euqual to "Sand1" but It
>> wont load it. If I set it as loader = pygame.image.load(loader) then it
>> sets the image to the variable loader. So I'm basically trying to set a
>> string equal to a surface variable. I dont want to have to go Sand1 =
>> pygame.image.load("Sand1.bmp") for every image because I'm expecting
>> there to be a lot of them when I am done.
> 
> 99% of the time, when you find yourself wanting to write things like:
> 
> sand1 = pygame.image.load("Sand1.bmp")
> sand2 = pygame.image.load("Sand2.bmp")
> sand3 = pygame.image.load("Sand3.bmp")
> ...
> sand99 = pygame.image.load("Sand99.bmp")
> 
> (or similar) you are going about it the wrong way. 
> 
> The better way is to do something like this:
> 
> sands = [None]
> filename = "Sand%d.bmp" # template for the file names
> for i in range(1, 100):  # start at 1 instead of 0
>     name = filename % i
>     sands.append(pygame.image.load(name))
> 
> 
> Once you've run that code, sands is a list holding all the images you 
> need.
> 
> (Note: The first item of the sands list is None, because lists are 
> numbered from 0 but your sands are numbered from 1. So we need to make an 
> adjustment.)
> 
> The second half is, how do you use the images?
> 
> Instead of writing something like this:
> 
> 
> draw(sand1)  # I don't actually know how to draw bitmaps in PyGame...
> draw(sand2)
> draw(sand3)
> ...
> draw(sand99)
> 
> 
> you would do something like this:
> 
> 
> for i in range(1, 100):
>     draw(sands[i])  # or whatever the real command is
> 
> 
> Does this help?
> 
> 
As Dennis already pointed out I like to use dictionaries in these cases, 
so I would use sand = dict() instead of sands = list()
and would do sand[i] = pygame.image.load(name)

Then you can retrieve the content by doing sand[your_number].

-- 
mph



More information about the Python-list mailing list