source: nagslang/level.py@ 348:f0e8970ab804

Last change on this file since 348:f0e8970ab804 was 348:f0e8970ab804, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Split out tiling into utility function

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