Saturday, November 24, 2012

Sprites and Tiles


My son finished his shooter game and I started to research tiles for the next project.

During Thanksgiving break, I started with Tiled TMX Loader.  This initially proved quite rewarding since there were several nice examples of Pygame code that shipped with the library.    I used Tiled Map Editor to make the maps from tile sets.

Since my son wants to show his friends his games on his phone, I was planning to package the Pygame application for his phone using Pygame Subset for Android (PGS4A).    

Unfortunately, when I did the build, I realized that Pygame Subset for Android does not support the XML libraries that Tiled TMX Loader requires.  There does not appear to be an easy way to build the XML C libraries into PGS4A or include a Python library with the application.    Here is a discussion thread from the Pygame Subset for Android forum.  The workaround people were using involved converting the tmx maps to JSON files and loading the map into the Pygame on Android application using the JSON module that was supported by PGS4A. 

Although Tiled can output a tile map to JSON, I realized that all the python JSON library does is load the JSON file data into dictionaries and lists that can then be accessed by the program.  Taking this route, I'm going to need to develop all the map camera movements, layer management, and collision detection myself.  Bummer.   The data is there, but I didn't want to think about how to manipulate it.

Feeling that manipulating map data from JSON files was too much of a task, I instead started to research sprites, basically shelving the idea for a complex map and focusing on understanding smaller lists and dictionaries of tiles made up of 32 x 32 pixel tiles.

piman's sprite tutorial was the most useful.  The application above is basically an extension of piman's tutorial.  Instead of colored rectangles, I used pygame.image.load("filename") to create image surfaces.  I used a single grass tile as the background and simply repeated it.

The controls at the bottom select the character to move.  

def select_character(buttons, mouse_pos, selection):
    selected_char = selection
    for b in buttons:
        if b.rect.collidepoint(mouse_pos):
            selected_char = b.character
    return(selected_char)

I recently realized that I can use pygame.Rect.collidepoint instead of pygame.Rect.colliderect.  The rectangles are the same ones that you use to blit the images onto the screen.

It's easy to get the mouse position with pygame.mouse.get_pos().

In the main event loop, I simply check for the mouse button up or down:
  • elif event.type == pygame.MOUSEBUTTONDOWN:
  • elif event.type == pygame.MOUSEBUTTONUP




No comments:

Post a Comment