source: nagslang/level.py@ 321:0d7885e2f063

Last change on this file since 321:0d7885e2f063 was 321:0d7885e2f063, checked in by Simon Cross <hodgestar@…>, 8 years ago

Add means for listing levels and areas.

File size: 7.7 KB
RevLine 
[50]1import pygame
2import pygame.locals as pgl
3
[145]4from nagslang import game_object as go
[168]5from nagslang import enemies
[201]6from nagslang import puzzle
[50]7from nagslang.resources import resources
[139]8from nagslang.yamlish import load, dump
[50]9
10POLY_COLORS = {
[53]11 1: pygame.color.THECOLORS['red'],
12 2: pygame.color.THECOLORS['green'],
13 3: pygame.color.THECOLORS['yellow'],
14 4: pygame.color.THECOLORS['blue'],
15 5: pygame.color.THECOLORS['lightblue'],
16 6: pygame.color.THECOLORS['magenta'],
17}
[50]18
19
[197]20LINE_COLOR = pygame.color.THECOLORS['orange']
21
22
[50]23class Level(object):
24
[277]25 def __init__(self, name, world):
[50]26 self.name = name
27 # defaults
28 self.x = 800
29 self.y = 600
30 self.polygons = {}
[197]31 self.lines = []
[277]32 self.world = world
[50]33 self.basetile = 'tiles/floor.png'
34 self._tile_image = None
35 self._surface = None
[95]36 self._exterior = False
[201]37 self._glue = puzzle.PuzzleGlue()
[191]38 self.drawables = []
39 self.overlay_drawables = []
[164]40 self._game_objects = []
[168]41 self._enemies = []
[50]42
[145]43 def _get_data(self):
44 # For overriding in tests.
[75]45 with resources.get_file('levels', self.name) as f:
[145]46 return load(f)
47
[164]48 def _dump_data(self, f):
49 # For manipulation in tests.
50 dump({
51 'size': [self.x, self.y],
52 'base_tile': self.basetile,
53 'polygons': self.polygons,
[197]54 'lines': self.lines,
[164]55 'game_objects': self._game_objects,
[168]56 'enemies': self._enemies,
[164]57 }, f)
58
[321]59 @classmethod
60 def list_levels(cls):
61 with resources.get_file('levels', 'LEVELS') as f:
62 levels = load(f)
63 return levels['levels']
64
[145]65 def load(self, space):
66 data = self._get_data()
[139]67 self.x, self.y = data['size']
[317]68 self.basetile = data['base_tile']
[139]69 for i, points in data['polygons'].iteritems():
70 self.polygons[i] = []
71 for point in points:
72 self.polygons[i].append(tuple(point))
[197]73 self.lines = data.get('lines', [])
[164]74 self._game_objects = data.get('game_objects', [])
75 for game_object_dict in self._game_objects:
[145]76 self._create_game_object(space, **game_object_dict)
[168]77 self._enemies = data.get('enemies', [])
78 for enemy_dict in self._enemies:
79 self._create_enemy(space, **enemy_dict)
[145]80
81 def _create_game_object(self, space, classname, args, name=None):
[209]82 modules = {
83 'game_object': go,
84 'puzzle': puzzle,
85 }
86 if '.' in classname:
87 module, classname = classname.split('.')
88 else:
89 module = 'game_object'
90 cls = getattr(modules[module], classname)
91
[201]92 if issubclass(cls, puzzle.Puzzler):
[145]93 gobj = cls(*args)
94 elif issubclass(cls, go.GameObject):
95 gobj = cls(space, *args)
[191]96 self.drawables.append(gobj)
97 if gobj.overlay:
98 self.overlay_drawables.append(gobj.overlay)
[145]99 else:
100 raise TypeError(
101 "Expected a subclass of Puzzler or GameObject, got %s" % (
102 classname))
103 if name is not None:
104 self._glue.add_component(name, gobj)
[274]105 return gobj
[50]106
[168]107 def _create_enemy(self, space, classname, args, name=None):
108 cls = getattr(enemies, classname)
109 if issubclass(cls, go.GameObject):
[277]110 gobj = cls(space, self.world, *args)
[191]111 self.drawables.append(gobj)
[168]112 else:
113 raise TypeError(
114 "Expected a subclass of GameObject, got %s" % (
115 classname))
116 if name is not None:
117 self._glue.add_component(name, gobj)
[274]118 return gobj
[168]119
[95]120 def all_closed(self):
121 """Check if all the polygons are closed"""
[72]122 closed = True
[122]123 messages = []
124 for index, poly in self.polygons.items():
[72]125 if len(poly) == 0:
126 # We ignore empty polygons
127 continue
128 elif len(poly) == 1:
129 closed = False
[122]130 messages.append("Error: polygon %s too small" % index)
[72]131 elif poly[-1] != poly[0]:
132 closed = False
[122]133 messages.append("Error: polygon %s not closed" % index)
134 return closed, messages
[95]135
136 def save(self):
[122]137 closed, _ = self.all_closed()
[72]138 if not closed:
[122]139 return False
[75]140 with resources.get_file('levels', self.name, mode='w') as f:
[164]141 self._dump_data(f)
[122]142 return True
[72]143
[50]144 def get_size(self):
145 return self.x, self.y
146
147 def set_base_tile(self, new_tile):
148 self.basetile = new_tile
149 self._tile_image = None
150
151 def point_to_pygame(self, pos):
152 # Convert a point from pymunk (which is what we store)
153 # to pygame for drawing
154 return (pos[0], self.y - pos[1])
155
156 def get_walls(self):
[197]157 walls = self.polygons.values()
158 walls.extend(self.lines)
159 return walls
[50]160
161 def _draw_walls(self):
162 for index, polygon in self.polygons.items():
163 color = POLY_COLORS[index]
164 if len(polygon) > 1:
165 pointlist = [self.point_to_pygame(p) for p in polygon]
166 pygame.draw.lines(self._surface, color, False, pointlist, 2)
[197]167 for line in self.lines:
168 pointlist = [self.point_to_pygame(p) for p in line]
169 pygame.draw.lines(self._surface, LINE_COLOR, False, pointlist, 2)
[50]170
171 def get_background(self):
172 self._draw_background()
[95]173 self._draw_exterior()
[50]174 # Draw polygons
175 self._draw_walls()
176 return self._surface
177
[95]178 def _draw_exterior(self, force=False):
179 """Fill the exterior of the level with black"""
180 if self._exterior and not force:
181 return
[118]182 white = pygame.color.THECOLORS['white']
183 black = pygame.color.THECOLORS['black']
[95]184 surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
[118]185 surface.fill(black)
[95]186 for index, polygon in self.polygons.items():
187 if len(polygon) > 1:
188 pointlist = [self.point_to_pygame(p) for p in polygon]
189 # filled polygons
[118]190 color = white
191 # If a polygon overlaps on of the existing polygons,
192 # it is treated as negative
193 # This is not a complete inversion, since any overlap
194 # triggers this (inversion is easy enough, but the
195 # behaviour doesn't seem useful)
196 # We also only check the vertexes - not breaking this
197 # assumption is left to the level designers
198 surface.lock()
199 for p in pointlist:
200 if surface.get_at(p) == white:
201 color = black
202 surface.unlock()
203 pygame.draw.polygon(surface, color, pointlist, 0)
[95]204 self._surface.blit(surface, (0, 0), special_flags=pgl.BLEND_RGBA_MULT)
205 self._exterior = True
206
[50]207 def _draw_background(self, force=False):
208 if self._tile_image is None:
209 self._tile_image = resources.get_image(self.basetile)
210 if self._surface is not None and not force:
211 # We assume we don't change
212 return self._surface
213 self._surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
214 self._surface.fill(pygame.color.THECOLORS['black'])
215 x_step = self._tile_image.get_rect().width
216 y_step = self._tile_image.get_rect().height
217 x_count = self.x // x_step + 1
218 y_count = self.y / y_step + 1
219 for x in range(x_count):
220 for y in range(y_count):
221 tile_rect = pygame.rect.Rect(x * x_step, y * y_step,
[98]222 x_step, y_step)
[50]223 self._surface.blit(self._tile_image, tile_rect)
224 return self._surface
Note: See TracBrowser for help on using the repository browser.