source: nagslang/level.py@ 346:282113d86d75

Last change on this file since 346:282113d86d75 was 346:282113d86d75, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Save door and lever state.

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