Guest User

Untitled

a guest
Jul 22nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.26 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4.  
  5.  
  6. import os
  7. import sys
  8. import pygame
  9. import math
  10. import time
  11. import random
  12. import pygame.surface
  13. from time import clock, time
  14. from pygame.locals import *
  15. import ConfigParser
  16.  
  17.  
  18.  
  19. pygame.init()
  20.  
  21. pygame.display.set_mode((640, 480))
  22. screen = pygame.display.get_surface()
  23.  
  24. MAP_TILE_WIDTH, MAP_TILE_HEIGHT = 48, 32
  25.  
  26. clock = pygame.time.Clock()
  27.  
  28. x = 1
  29.  
  30.  
  31. class TileCache(object):
  32. """Load the tilesets lazily into global cache"""
  33.  
  34. def __init__(self, width=64, height= None):
  35. self.width = width
  36. self.height = height or width
  37. self.cache = {}
  38.  
  39. def __getitem__(self, filename):
  40. """Return a table of tiles, load it from disk if needed."""
  41.  
  42. key = (filename, self.width, self.height)
  43. try:
  44. return self.cache[key]
  45. except KeyError:
  46. tile_table = self._load_tile_table(filename, self.width,
  47. self.height)
  48. self.cache[key] = tile_table
  49. return tile_table
  50.  
  51. def _load_tile_table(self, filename, width, height):
  52. """Load an image and split it into tiles."""
  53.  
  54. image = pygame.image.load(filename).convert()
  55. image.set_colorkey((0, 0, 0))
  56. image_width, image_height = image.get_size()
  57. tile_table = []
  58. for tile_x in range(0, image_width/width):
  59. line = []
  60. tile_table.append(line)
  61. for tile_y in range(0, image_height/height):
  62. rect = (tile_x*width, tile_y*height, width, height)
  63. line.append(image.subsurface(rect))
  64. return tile_table
  65.  
  66.  
  67. class Level(object):
  68. def load_file(self, filename="level1.map"):
  69. self.tileset = ''
  70. self.map = []
  71. self.items = {}
  72. self.key = {}
  73. self.width = 0
  74. self.height = 0
  75. parser = ConfigParser.ConfigParser()
  76. parser.read(filename)
  77. self.tileset = parser.get("level", "tileset")
  78. self.map = parser.get("level", "map").split("\n")
  79. for section in parser.sections():
  80. if len(section) == 1:
  81. desc = dict(parser.items(section))
  82. self.key[section] = desc
  83. self.width = len(self.map[0])
  84. self.height = len(self.map)
  85. for y, line in enumerate(self.map):
  86. for x, c in enumerate(line):
  87. if not self.is_wall(x, y) and 'sprite' in self.key[c]:
  88. self.items[(x, y)] = self.key[c]
  89. def get_tile(self, x, y):
  90. try:
  91. char = self.map[y][x]
  92. except IndexError:
  93. return {}
  94. try:
  95. return self.key[char]
  96.  
  97. except KeyError:
  98. return {}
  99. def get_bool(self, x, y, name):
  100. """Tell if the specified flag is set for position on the map."""
  101.  
  102. value = self.get_tile(x, y).get(name)
  103. return value in (True, 1, 'true', 'yes', 'True', 'Yes', '1', 'on', 'On')
  104.  
  105. def is_wall(self, x, y):
  106. """Is there a wall?"""
  107.  
  108. return self.get_bool(x, y, 'wall')
  109.  
  110. def is_blocking(self, x, y):
  111. """Is this place blocking movement?"""
  112.  
  113. if not 0 <= x < self.width or not 0 <= y < self.height:
  114. return True
  115. return self.get_bool(x, y, 'block')
  116.  
  117. def render(self):
  118. wall = self.is_wall
  119. tiles = MAP_CACHE[self.tileset]
  120. image = pygame.Surface((self.width*MAP_TILE_WIDTH, self.height*MAP_TILE_HEIGHT))
  121. overlays = {}
  122. for map_y, line in enumerate(self.map):
  123. for map_x, c in enumerate(line):
  124. if wall(map_x, map_y):
  125. # Draw different tiles depending on neighbourhood
  126. if not wall(map_x, map_y+1):
  127. if wall(map_x+1, map_y) and wall(map_x-1, map_y):
  128. tile = 1, 2
  129. elif wall(map_x+1, map_y):
  130. tile = 0, 2
  131. elif wall(map_x-1, map_y):
  132. tile = 2, 2
  133. else:
  134. tile = 3, 2
  135. else:
  136. if wall(map_x+1, map_y+1) and wall(map_x-1, map_y+1):
  137. tile = 1, 1
  138. elif wall(map_x+1, map_y+1):
  139. tile = 0, 1
  140. elif wall(map_x-1, map_y+1):
  141. tile = 2, 1
  142. else:
  143. tile = 3, 1
  144. # Add overlays if the wall may be obscuring something
  145. if not wall(map_x, map_y-1):
  146. if wall(map_x+1, map_y) and wall(map_x-1, map_y):
  147. over = 1, 0
  148. elif wall(map_x+1, map_y):
  149. over = 0, 0
  150. elif wall(map_x-1, map_y):
  151. over = 2, 0
  152. else:
  153. over = 3, 0
  154. overlays[(map_x, map_y)] = tiles[over[0]][over[1]]
  155. else:
  156. try:
  157. tile = self.key[c]['tile'].split(',')
  158. tile = int(tile[0]), int(tile[1])
  159. except (ValueError, KeyError):
  160. # Default to ground tile
  161. tile = 0, 3
  162. tile_image = tiles[tile[0]][tile[1]]
  163. image.blit(tile_image,
  164. (map_x*MAP_TILE_WIDTH, map_y*MAP_TILE_HEIGHT))
  165. return image, overlays
  166.  
  167.  
  168.  
  169.  
  170.  
  171.  
  172.  
  173. class Sprite(pygame.sprite.Sprite):
  174. """Sprite for animated items and base class for Player."""
  175.  
  176. is_player = False
  177.  
  178. def __init__(self, pos=(0, 0), frames=None):
  179. super(Sprite, self).__init__()
  180. self.frames = frames
  181. self.image = self.frames[0][0]
  182. self.rect = self.image.get_rect()
  183. self.animation = self.stand_animation()
  184. self.pos = pos
  185.  
  186. def _get_pos(self):
  187. """Check the current position of the sprite on the map."""
  188.  
  189. return (self.rect.midbottom[0]-24)/48, (self.rect.midbottom[1]-32)/32
  190.  
  191. def _set_pos(self, pos):
  192. """Set the position and depth of the sprite on the map."""
  193.  
  194. self.rect.midbottom = pos[0]*48+24, pos[1]*32+32
  195. self.depth = self.rect.midbottom[1]
  196.  
  197. pos = property(_get_pos, _set_pos)
  198.  
  199. def move(self, dx, dy):
  200. """Change the position of the sprite on screen."""
  201.  
  202. self.rect.move_ip(dx, dy)
  203. self.depth = self.rect.midbottom[1]
  204.  
  205. def stand_animation(self):
  206. """The default animation."""
  207.  
  208. while True:
  209. # Change to next frame every two ticks
  210. for frame in self.frames[0]:
  211. self.image = frame
  212. yield None
  213. yield None
  214.  
  215. def update(self, *args):
  216. """Run the current animation."""
  217.  
  218. self.animation.next()
  219.  
  220.  
  221.  
  222.  
  223. class SortedUpdates(pygame.sprite.RenderUpdates):
  224. """A sprite group that sorts them by depth."""
  225.  
  226. def sprites(self):
  227. """The list of sprites in the group, sorted by depth."""
  228.  
  229. return sorted(self.spritedict.keys(), key=lambda sprite: sprite.depth)
  230.  
  231.  
  232. class Player:
  233. def drawit(self, screen):
  234. self.character = pygame.image.load("hymio.png")
  235. screen.blit(self.character, (288, 208))
  236.  
  237.  
  238.  
  239. MAP_CACHE = TileCache(MAP_TILE_WIDTH, MAP_TILE_HEIGHT)
  240.  
  241. level = Level()
  242. level.load_file('level1.map')
  243. player = Player()
  244.  
  245. background, overlay_dict = level.render()
  246.  
  247. sprites = pygame.sprite.RenderUpdates()
  248.  
  249.  
  250. overlays = pygame.sprite.RenderUpdates()
  251.  
  252.  
  253. for (x, y), image in overlay_dict.iteritems():
  254. overlay = pygame.sprite.Sprite(overlays)
  255. overlay.image = image
  256. overlay.rect = image.get_rect().move(x*48, y*32-32)
  257.  
  258. SPRITE_CACHE = TileCache(64, 64)
  259.  
  260.  
  261. for pos, tile in level.items.iteritems():
  262. sprite = Sprite(pos, SPRITE_CACHE[tile["sprite"]])
  263. sprites.add(sprite)
  264. sprites.clear(screen, background)
  265.  
  266.  
  267. while True:
  268.  
  269. sprite.move(-1, 0) #this should move the sprites, but it only moves one of them.
  270.  
  271. screen.blit(background, (0 + x, 0))
  272.  
  273.  
  274. sprites.draw(screen)
  275.  
  276.  
  277. overlays.draw(screen)
  278. player.drawit(screen)
  279. pygame.display.flip()
  280.  
  281.  
  282. sprites.update()
  283. x = x - 1
  284. clock.tick(15)
Add Comment
Please, Sign In to add comment