source: nagslang/level.py@ 433:8cd9828828c0

Last change on this file since 433:8cd9828828c0 was 433:8cd9828828c0, checked in by Neil Muller <drnlmuller@…>, 8 years ago

PEP8

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