source: nagslang/level.py@ 274:988cf7c8b402

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

Add object returns for use in the level editor

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