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