tileset.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import struct
  2. from xml.etree import ElementTree
  3. import pygame
  4. class Tileset(object):
  5. tilesize = 16
  6. RIGHT = 0
  7. DOWN = 1
  8. LEFT = 2
  9. UP = 3
  10. def __init__(self, screen):
  11. self.screen = screen
  12. image = pygame.image.load('tileset.png').convert()
  13. self.tileset = {
  14. self.RIGHT: image,
  15. self.UP: pygame.transform.rotate(image, 90),
  16. self.LEFT: pygame.transform.rotate(image, 180),
  17. self.DOWN: pygame.transform.rotate(image, 270),
  18. }
  19. self.tile_width, self.tile_height = image.get_size()
  20. self.tile_width /= self.tilesize
  21. self.tile_height /= self.tilesize
  22. def _render(self, tile_x, tile_y, pos, direction=RIGHT):
  23. tileset = self.tileset[direction]
  24. if direction == self.RIGHT:
  25. x, y = tile_x, tile_y
  26. elif direction == self.UP:
  27. x, y = tile_y, self.tile_width - tile_x - 1
  28. elif direction == self.LEFT:
  29. x, y = self.tile_width - tile_x - 1, self.tile_height - tile_y - 1
  30. elif direction == self.DOWN:
  31. x, y = self.tile_height -tile_y - 1, tile_x
  32. x *= self.tilesize
  33. y *= self.tilesize
  34. self.screen.blit(tileset, pos, (x, y, self.tilesize, self.tilesize))
  35. def render_person(self, pos, direction):
  36. self._render(0, 13, pos, direction)
  37. def load_level(self): # https://bitbucket.org/r1chardj0n3s/pygame-tutorial/src/a383dd24790d/tmx.py#cl-241
  38. level_data = ElementTree.parse('level1.tmx').getroot()
  39. raw_data = level_data.findall('layer')[0].findall('data')[0].text.strip()
  40. data = raw_data.decode('base64').decode('zlib')
  41. # read as array of 4-byte ints
  42. self.level_array = struct.unpack('<{}i'.format(len(data)/4), data)
  43. def render_level(self):
  44. for i, tile in enumerate(self.level_array):
  45. x, y = divmod(i, 50)
  46. x *= self.tilesize
  47. y *= self.tilesize
  48. tile_y, tile_x = divmod(tile - 1, self.tilesize) # those 1-indexing fuckers
  49. self._render(tile_x, tile_y, (y, x))