view tiling.py @ 1:17e9c6f3a0dd default tip

isolate into a function
author Radomir Dopieralski <sheep-devel@sheep.art.pl>
date Sun, 10 Mar 2013 20:45:29 +0100
parents 88a19853b1ac
children
line wrap: on
line source

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pygame


def load_atlas(filename, width=32, height=None):
    image = pygame.image.load(filename)
    image_width, image_height = image.get_size()
    w, h = width, height or width
    return [
        image.subsurface((x * w, y * h, w, h))
        for y in xrange(0, image_height // h)
        for x in xrange(0, image_width // w)
    ]

def render_grid(surf, grid, tiles):
    for y, (row, nrow) in enumerate(zip(grid, grid[1:])):
        for x, (tl, tr, bl, br) in enumerate(zip(row, row[1:], nrow, nrow[1:])):
            surf.blit(grass[tl + tr * 2 + bl * 4 + br * 8], (x * 48, y * 32))


if __name__ == '__main__':
    screen = pygame.display.set_mode((480, 480))
    grass = load_atlas('grass_on_ground.png', 48, 32)
    grid = [
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0],
        [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0],
        [0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0],
        [0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0],
        [0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0],
        [0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
        [0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0],
        [0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0],
        [0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0],
        [0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0],
        [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
        [0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0],
        [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0],
        [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    ]
    render_grid(screen, grid, grass)
    pygame.display.flip()
    while pygame.event.wait().type not in {pygame.QUIT, pygame.KEYDOWN}:
        pass