Mercurial > pygame-tutorial
view 001/006.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 | 2661d2091f1d |
| children |
line wrap: on
line source
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygame import pygame.locals as pg LEVEL_MAP = [ "XXXXXXXXXXXXXXXXXXXXXXXXX", "X.......................X", "X.XXXXXXXXXX.XXXXXXXXXX.X", "X.X......X.X..........X.X", "X.X..X.XXX.X.XXXXXXXXXX.X", "X.XXXX.....X.......X..X.X", "X......XXXXXXXXXXX.X..X.X", "X.XX.X.X.........X....X.X", "X.X..X...........X.X..X.X", "X.X..X.X.........X.X..X.X", "X.X..X.XXXXXXXXXXX.XXXX.X", "X.XXXX..................X", "X.X..X.XXXXXXXXXXXXXXXX.X", "X.X..X................X.X", "X.X....X..............X.X", "X.XXXX.XXXXXXXXXXXXXXXX.X", "X.......................X", "XXXXXXXXXXXXXXXXXXXXXXXXX", ] class Level(object): def __init__(self, level_map): self.level_map = [list(row) for row in level_map] self.hero_position = 1, 1 self[self.hero_position] = '@' def __setitem__(self, (x, y), square): self.level_map[y][x] = square def __getitem__(self, (x, y)): return self.level_map[y][x] def render(self, screen, images): for y, row in enumerate(self.level_map): for x, square in enumerate(row): screen.blit(images[square], (x * 32, y * 32)) def move_hero(self, (dx, dy)): x, y = self.hero_position if self[x + dx, y + dy] == '.': self[self.hero_position] = '.' self.hero_position = x + dx, y + dy self[self.hero_position] = '@' class Game(object): def __init__(self): pygame.display.init() self.screen = pygame.display.set_mode((800, 600)) self.screen.fill((0x66, 0x66, 0x66)) self.images = { 'X': pygame.image.load('wall.png').convert(), '.': pygame.image.load('dirt.png').convert(), '@': pygame.image.load('hero.png').convert(), } 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, level_map): self.level = Level(level_map) 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, self.images) 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_MAP) game.run()
