[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] Tile Based games



Leonardo Santagada wrote:

> I've been trying to make a tile based game for pygame. I'm having problens
> in how to buffer the tiles while scrolling the map. I just don't know how to
> do it. Now I have given up and i'm bliting the tiles directly to the screen
> but it doesn't seen like a good idea. Also this way I can't make smooth
> scrolling (in 16x16 tiles make then scroll by 2 or 4 pixel at a time). I
> have searched a lot for this but in every tile tutorial they only talk about
> how to organize the map structure, not how to draw the tiles. Could someone
> give me a hand at this?

from what i've found, when you are scrolling, the best bet is usually 
just to redraw the entire screen each frame. one benefit to this method 
is it works very well with hardware accelerated surfaces (if you can get 
one). when stuck in a software mode, you'll likely be around 25fps on 
average hardare. 25fps actually seems like enough for most 
sidescrollers. this also frees you from needing to keep track of updated 
rectangles on the screen, which is simpler.

anyways, drawing the map tiles is actually the simple part, managing 
them is where the work comes in. for drawing here's a simple type of 
function. this is pretty generic, so you can definitely speed it up by 
hardcoding parts of the logic in...

#warning, code typed straight into email, may not fly :]
#the "map" argument here is some class you create that handles
#the map data. the only information we need from it to draw is
#the size of each tile (16,16), and a function to get the Surface
#for any position (returns None if position is "outside" of the map)

def drawtiles(screen, map, posx, posy):
     screenx, screeny = screen.get_size()
     tilex, tiley = map.get_tile_size()
     offsetx, offsety = posx % tilex, posy % tiley
     startx, starty = posx / tilex, posy / tiley

     for y in range(tiley / screeny + 1):
         mapy = y + starty
         pixely = (y - 1) * tiley + offsety
         for x in range(tilex / screenx + 1):
             mapx = x + startx
             pixelx = (x - 1) * tilex + offsetx

             img = map.get_image(mapx, mapy)
             if img is not None:
                 screen.blit(img, (pixelx, pixely))
             else: #off edge of map, fill with red
                 r = Rect(pixelx, pixely, tilex, tiley)
                 screen.fill((255, 0, 0), r)


there you have it. this _should_ draw your map on the screen. the "posx" 
and "posy" arguments you pass are pixel offsets, so it is easy to scroll 
the map by "2 pixels"

hopefully this gets you going on your tile-drawing quests!

____________________________________
pygame mailing list
pygame-users@seul.org
http://pygame.seul.org