pythonpython-3.xpygame

How do I use sprite sheets in Pygame?


The only way I know how to make an animation is by using individual images (as in 1 image per file). I got a sprite sheet but I don't want to spend the time cropping each individual sprite out.

I am using Python 3.2.


Solution

  • It really isn't very hard to do… but the best sample code I found in a quick search is also a usable library that does the work for you: spritesheet, right from the pygame wiki.

    So, you can start off by just using that. I'd give you an example tailored to your use case, but you haven't given us any idea what your code looks like or what you want to do, so I can't possibly give you anything better than is already on that page, so:

    import spritesheet
    ...
    ss = spritesheet.spritesheet('somespritesheet.png')
    # Sprite is 16x16 pixels at location 0,0 in the file...
    image = ss.image_at((0, 0, 16, 16))
    images = []
    # Load two images into an array, their transparent bit is (255, 255, 255)
    images = ss.images_at((0, 0, 16, 16),(17, 0, 16,16), colorkey=(255, 255, 255))
    …
    

    Meanwhile, you can read the (very simple) code in that spritesheet class to understand how it works.