Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

python - how to load an image to a grid using pygame, instead of just using a fill color?

I am trying to create a "map of a city" using pygame. I want to be able to put images of buildings in specific grid coords rather than just filling them in with a color.

This is how I am creating this map grid:

def clear():
    for r in range(rows):
        for c in range(rows):
            if r%3 == 1 and c%3 == 1:
                color = brown;
                grid[r][c] = 1;
            else:
                color = white;
                grid[r][c] = 0; 
            pygame.draw.rect(screen, color, [(margin+width)*c+margin, (margin+height)*r+margin, width, height])         
    pygame.display.flip();

Now how do I put images of buildings in those brown colored grids at those specific locations? I've tried some of the samples online but can't seem to get them to work. Any help is appreciated.

If anyone have a good source for free sprites that I can use for pygame, please let me know. Thanks!

this is the grid map i created

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example I wrote. It uses a numpy to store tile data. The code plus image is downloadable at: http://code.google.com/p/ninmonkey/source/.../maptiles (If that fails, use this url: https://storage.googleapis.com/google-code-archive-source/v2/code.google.com/ninmonkey/source-archive.zip )

  • Press S to toggle mouse scrolling.
  • Map.tiles is a 2d numpy.array that stores tile's id

tileset demo

If you want to add units/sprites that are on top of the tilemap: (Your buildings might count as this)

  • store location using world coordinates
  • draw them using a world2screen coordinate function.

The function will add the map offset to their world coordinates. So if the map offset is (-100,0) and your unit's world coordinate is (0,0), you render at (-100,0) placing them a the top left part of the map, as expected, even though you are scrolled.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...