tileset.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. PLAYER = 209
  11. ENEMY1 = 161
  12. def __init__(self, screen):
  13. self.screen = screen
  14. image = pygame.image.load('tileset.png').convert()
  15. self.tileset = {
  16. self.RIGHT: image,
  17. self.UP: pygame.transform.rotate(image, 90),
  18. self.LEFT: pygame.transform.rotate(image, 180),
  19. self.DOWN: pygame.transform.rotate(image, 270),
  20. }
  21. self.tile_width, self.tile_height = image.get_size()
  22. self.tile_width /= self.TILESIZE
  23. self.tile_height /= self.TILESIZE
  24. def _render(self, tile_x, tile_y, pos, direction=RIGHT):
  25. tileset = self.tileset[direction]
  26. if direction == self.RIGHT:
  27. x, y = tile_x, tile_y
  28. elif direction == self.UP:
  29. x, y = tile_y, self.tile_width - tile_x - 1
  30. elif direction == self.LEFT:
  31. x, y = self.tile_width - tile_x - 1, self.tile_height - tile_y - 1
  32. elif direction == self.DOWN:
  33. x, y = self.tile_height -tile_y - 1, tile_x
  34. x *= self.TILESIZE
  35. y *= self.TILESIZE
  36. self.screen.blit(tileset, pos, (x, y, self.TILESIZE, self.TILESIZE))
  37. def render_person(self, pos, direction):
  38. self._render(0, 13, pos, direction)
  39. def load_level(self): # https://bitbucket.org/r1chardj0n3s/pygame-tutorial/src/a383dd24790d/tmx.py#cl-241
  40. level_data = ElementTree.parse('level1.tmx').getroot()
  41. layers = level_data.findall('layer')
  42. if len(layers) != 2:
  43. raise Exception('expected 2 layers: level and units')
  44. loaded = {}
  45. for layer in layers:
  46. name = layer.attrib['name']
  47. raw_data = layer.findall('data')[0].text.strip()
  48. data = raw_data.decode('base64').decode('zlib')
  49. # read as array of 4-byte ints
  50. array = list(struct.unpack('<{}i'.format(len(data)/4), data))
  51. loaded[name] = array
  52. self.level_array = loaded['level']
  53. units = {
  54. self.ENEMY1: [],
  55. self.PLAYER: [],
  56. }
  57. for i, tile in enumerate(loaded['units']):
  58. if tile in units.iterkeys():
  59. y, x = divmod(i, 50)
  60. units[tile].append((x, y))
  61. if len(units[self.PLAYER]) != 1:
  62. raise Exception('expected exactly 1 player tile in units layer, found ' + str(len(units[self.PLAYER])))
  63. return units
  64. def render_level(self):
  65. for i, tile in enumerate(self.level_array):
  66. y, x = divmod(i, 50)
  67. x *= self.TILESIZE
  68. y *= self.TILESIZE
  69. tile_y, tile_x = divmod(tile - 1, self.TILESIZE) # those 1-indexing fuckers
  70. self._render(tile_x, tile_y, (x, y))