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
RevLine 
[50]1import pygame
2import pygame.locals as pgl
3
[145]4from nagslang import game_object as go
[168]5from nagslang import enemies
[201]6from nagslang import puzzle
[50]7from nagslang.resources import resources
[139]8from nagslang.yamlish import load, dump
[50]9
10POLY_COLORS = {
[53]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}
[50]18
19
[197]20LINE_COLOR = pygame.color.THECOLORS['orange']
21
22
[50]23class Level(object):
24
[277]25 def __init__(self, name, world):
[50]26 self.name = name
27 # defaults
28 self.x = 800
29 self.y = 600
30 self.polygons = {}
[197]31 self.lines = []
[277]32 self.world = world
[346]33 self.world.level_state.setdefault(name, {})
[50]34 self.basetile = 'tiles/floor.png'
35 self._tile_image = None
36 self._surface = None
[95]37 self._exterior = False
[201]38 self._glue = puzzle.PuzzleGlue()
[191]39 self.drawables = []
40 self.overlay_drawables = []
[164]41 self._game_objects = []
[168]42 self._enemies = []
[50]43
[145]44 def _get_data(self):
45 # For overriding in tests.
[75]46 with resources.get_file('levels', self.name) as f:
[145]47 return load(f)
48
[164]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,
[197]55 'lines': self.lines,
[164]56 'game_objects': self._game_objects,
[168]57 'enemies': self._enemies,
[164]58 }, f)
59
[321]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
[145]66 def load(self, space):
67 data = self._get_data()
[139]68 self.x, self.y = data['size']
[317]69 self.basetile = data['base_tile']
[139]70 for i, points in data['polygons'].iteritems():
71 self.polygons[i] = []
72 for point in points:
73 self.polygons[i].append(tuple(point))
[197]74 self.lines = data.get('lines', [])
[164]75 self._game_objects = data.get('game_objects', [])
76 for game_object_dict in self._game_objects:
[145]77 self._create_game_object(space, **game_object_dict)
[168]78 self._enemies = data.get('enemies', [])
79 for enemy_dict in self._enemies:
80 self._create_enemy(space, **enemy_dict)
[145]81
82 def _create_game_object(self, space, classname, args, name=None):
[209]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
[201]93 if issubclass(cls, puzzle.Puzzler):
[145]94 gobj = cls(*args)
95 elif issubclass(cls, go.GameObject):
96 gobj = cls(space, *args)
[346]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
[191]105 self.drawables.append(gobj)
106 if gobj.overlay:
107 self.overlay_drawables.append(gobj.overlay)
[145]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)
[274]114 return gobj
[50]115
[168]116 def _create_enemy(self, space, classname, args, name=None):
117 cls = getattr(enemies, classname)
118 if issubclass(cls, go.GameObject):
[277]119 gobj = cls(space, self.world, *args)
[191]120 self.drawables.append(gobj)
[168]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)
[274]127 return gobj
[168]128
[95]129 def all_closed(self):
130 """Check if all the polygons are closed"""
[72]131 closed = True
[122]132 messages = []
133 for index, poly in self.polygons.items():
[72]134 if len(poly) == 0:
135 # We ignore empty polygons
136 continue
137 elif len(poly) == 1:
138 closed = False
[122]139 messages.append("Error: polygon %s too small" % index)
[72]140 elif poly[-1] != poly[0]:
141 closed = False
[122]142 messages.append("Error: polygon %s not closed" % index)
143 return closed, messages
[95]144
145 def save(self):
[122]146 closed, _ = self.all_closed()
[72]147 if not closed:
[122]148 return False
[75]149 with resources.get_file('levels', self.name, mode='w') as f:
[164]150 self._dump_data(f)
[122]151 return True
[72]152
[50]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):
[197]166 walls = self.polygons.values()
167 walls.extend(self.lines)
168 return walls
[50]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)
[197]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)
[50]179
180 def get_background(self):
181 self._draw_background()
[95]182 self._draw_exterior()
[50]183 # Draw polygons
184 self._draw_walls()
185 return self._surface
186
[95]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
[118]191 white = pygame.color.THECOLORS['white']
192 black = pygame.color.THECOLORS['black']
[95]193 surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
[118]194 surface.fill(black)
[95]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
[118]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)
[95]213 self._surface.blit(surface, (0, 0), special_flags=pgl.BLEND_RGBA_MULT)
214 self._exterior = True
215
[50]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,
[98]231 x_step, y_step)
[50]232 self._surface.blit(self._tile_image, tile_rect)
233 return self._surface
Note: See TracBrowser for help on using the repository browser.