Mercurial > pygame-tutorial
view 002/004.py @ 12:9dc97f88e274 default tip
Added CC0 license
| author | Radomir Dopieralski <sheep-devel@sheep.art.pl> |
|---|---|
| date | Sun, 08 Jul 2012 19:56:38 +0200 |
| parents | 96fffc932ba7 |
| children |
line wrap: on
line source
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygame import pygame.locals as pg from pytmx import tmxloader def load_sheet(filename, width=32, height=None): if height is None: height = width image = pygame.image.load(filename) image = image.convert() image.set_colorkey((0xff, 0, 0xff)) w, h = image.get_size() images = [] for x in xrange(w // width): for y in xrange(h // height): rect = pygame.rect.Rect(x * width, y * height, width, height) images.append(image.subsurface(rect)) return images class Level(object): def __init__(self, filename): self.tiled_map = tmxloader.load_pygame(filename) self.hero_position = 1, 1 self.spritesheet = load_sheet('spritesheet.png', 64) def render(self, screen): w = self.tiled_map.tilewidth h = self.tiled_map.tileheight get_image = self.tiled_map.getTileImage for l, layer in enumerate(self.tiled_map.tilelayers): for y in xrange(self.tiled_map.height): for x in xrange(self.tiled_map.width): image = get_image(x, y, l) if image: screen.blit(image, (x * w, y * h)) x, y = self.hero_position screen.blit(self.spritesheet[2], (x * 32 - 16, y * 32 - 32)) def move_hero(self, (dx, dy)): x, y = self.hero_position self.hero_position = x + dx, y + dy class Game(object): def __init__(self): pygame.display.init() pygame.font.init() self.screen = pygame.display.set_mode((800, 600)) self.screen.fill((0x66, 0x66, 0x66)) self.keys = { pg.K_UP: (self.move_hero, (0, -1)), pg.K_DOWN: (self.move_hero, (0, 1)), pg.K_LEFT: (self.move_hero, (-1, 0)), pg.K_RIGHT: (self.move_hero, (1, 0)), pg.K_ESCAPE: (self.quit,), } def load_level(self, filename): self.level = Level(filename) def quit(self): self.game_over = True def move_hero(self, direction): self.level.move_hero(direction) def control(self): event = pygame.event.wait() if event.type == pg.QUIT: self.quit() elif event.type == pg.KEYDOWN: try: action = self.keys[event.key] except KeyError: pass else: action[0](*action[1:]) def display(self): self.level.render(self.screen) pygame.display.update() def run(self): self.game_over = False while not self.game_over: self.display() self.control() if __name__ == '__main__': game = Game() game.load_level('level.tmx') game.run()
