source: nagslang/level.py@ 378:8069c9be1c3e

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

Create a nagslang.collectable module for collectables

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