source: nagslang/level.py@ 437:d087dfb10896

Last change on this file since 437:d087dfb10896 was 437:d087dfb10896, checked in by Stefano Rivera <stefano@…>, 8 years ago

Replace menu and death screen with the starting level

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