1 | import pygame
|
---|
2 | import pygame.locals as pgl
|
---|
3 |
|
---|
4 | from nagslang import game_object as go
|
---|
5 | from nagslang import enemies
|
---|
6 | from nagslang import puzzle
|
---|
7 | from nagslang.resources import resources
|
---|
8 | from nagslang.yamlish import load, dump
|
---|
9 |
|
---|
10 | POLY_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 |
|
---|
20 | LINE_COLOR = pygame.color.THECOLORS['orange']
|
---|
21 |
|
---|
22 |
|
---|
23 | class 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 |
|
---|
99 | def _create_enemy(self, space, classname, args, name=None):
|
---|
100 | cls = getattr(enemies, classname)
|
---|
101 | if issubclass(cls, go.GameObject):
|
---|
102 | gobj = cls(space, *args)
|
---|
103 | self.drawables.append(gobj)
|
---|
104 | else:
|
---|
105 | raise TypeError(
|
---|
106 | "Expected a subclass of GameObject, got %s" % (
|
---|
107 | classname))
|
---|
108 | if name is not None:
|
---|
109 | self._glue.add_component(name, gobj)
|
---|
110 |
|
---|
111 | def all_closed(self):
|
---|
112 | """Check if all the polygons are closed"""
|
---|
113 | closed = True
|
---|
114 | messages = []
|
---|
115 | for index, poly in self.polygons.items():
|
---|
116 | if len(poly) == 0:
|
---|
117 | # We ignore empty polygons
|
---|
118 | continue
|
---|
119 | elif len(poly) == 1:
|
---|
120 | closed = False
|
---|
121 | messages.append("Error: polygon %s too small" % index)
|
---|
122 | elif poly[-1] != poly[0]:
|
---|
123 | closed = False
|
---|
124 | messages.append("Error: polygon %s not closed" % index)
|
---|
125 | return closed, messages
|
---|
126 |
|
---|
127 | def save(self):
|
---|
128 | closed, _ = self.all_closed()
|
---|
129 | if not closed:
|
---|
130 | return False
|
---|
131 | with resources.get_file('levels', self.name, mode='w') as f:
|
---|
132 | self._dump_data(f)
|
---|
133 | return True
|
---|
134 |
|
---|
135 | def get_size(self):
|
---|
136 | return self.x, self.y
|
---|
137 |
|
---|
138 | def set_base_tile(self, new_tile):
|
---|
139 | self.basetile = new_tile
|
---|
140 | self._tile_image = None
|
---|
141 |
|
---|
142 | def point_to_pygame(self, pos):
|
---|
143 | # Convert a point from pymunk (which is what we store)
|
---|
144 | # to pygame for drawing
|
---|
145 | return (pos[0], self.y - pos[1])
|
---|
146 |
|
---|
147 | def get_walls(self):
|
---|
148 | walls = self.polygons.values()
|
---|
149 | walls.extend(self.lines)
|
---|
150 | return walls
|
---|
151 |
|
---|
152 | def _draw_walls(self):
|
---|
153 | for index, polygon in self.polygons.items():
|
---|
154 | color = POLY_COLORS[index]
|
---|
155 | if len(polygon) > 1:
|
---|
156 | pointlist = [self.point_to_pygame(p) for p in polygon]
|
---|
157 | pygame.draw.lines(self._surface, color, False, pointlist, 2)
|
---|
158 | for line in self.lines:
|
---|
159 | pointlist = [self.point_to_pygame(p) for p in line]
|
---|
160 | pygame.draw.lines(self._surface, LINE_COLOR, False, pointlist, 2)
|
---|
161 |
|
---|
162 | def get_background(self):
|
---|
163 | self._draw_background()
|
---|
164 | self._draw_exterior()
|
---|
165 | # Draw polygons
|
---|
166 | self._draw_walls()
|
---|
167 | return self._surface
|
---|
168 |
|
---|
169 | def _draw_exterior(self, force=False):
|
---|
170 | """Fill the exterior of the level with black"""
|
---|
171 | if self._exterior and not force:
|
---|
172 | return
|
---|
173 | white = pygame.color.THECOLORS['white']
|
---|
174 | black = pygame.color.THECOLORS['black']
|
---|
175 | surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
|
---|
176 | surface.fill(black)
|
---|
177 | for index, polygon in self.polygons.items():
|
---|
178 | if len(polygon) > 1:
|
---|
179 | pointlist = [self.point_to_pygame(p) for p in polygon]
|
---|
180 | # filled polygons
|
---|
181 | color = white
|
---|
182 | # If a polygon overlaps on of the existing polygons,
|
---|
183 | # it is treated as negative
|
---|
184 | # This is not a complete inversion, since any overlap
|
---|
185 | # triggers this (inversion is easy enough, but the
|
---|
186 | # behaviour doesn't seem useful)
|
---|
187 | # We also only check the vertexes - not breaking this
|
---|
188 | # assumption is left to the level designers
|
---|
189 | surface.lock()
|
---|
190 | for p in pointlist:
|
---|
191 | if surface.get_at(p) == white:
|
---|
192 | color = black
|
---|
193 | surface.unlock()
|
---|
194 | pygame.draw.polygon(surface, color, pointlist, 0)
|
---|
195 | self._surface.blit(surface, (0, 0), special_flags=pgl.BLEND_RGBA_MULT)
|
---|
196 | self._exterior = True
|
---|
197 |
|
---|
198 | def _draw_background(self, force=False):
|
---|
199 | if self._tile_image is None:
|
---|
200 | self._tile_image = resources.get_image(self.basetile)
|
---|
201 | if self._surface is not None and not force:
|
---|
202 | # We assume we don't change
|
---|
203 | return self._surface
|
---|
204 | self._surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
|
---|
205 | self._surface.fill(pygame.color.THECOLORS['black'])
|
---|
206 | x_step = self._tile_image.get_rect().width
|
---|
207 | y_step = self._tile_image.get_rect().height
|
---|
208 | x_count = self.x // x_step + 1
|
---|
209 | y_count = self.y / y_step + 1
|
---|
210 | for x in range(x_count):
|
---|
211 | for y in range(y_count):
|
---|
212 | tile_rect = pygame.rect.Rect(x * x_step, y * y_step,
|
---|
213 | x_step, y_step)
|
---|
214 | self._surface.blit(self._tile_image, tile_rect)
|
---|
215 | return self._surface
|
---|