source: nagslang/level.py@ 191:e080fcd07fa9

Last change on this file since 191:e080fcd07fa9 was 191:e080fcd07fa9, checked in by Stefano Rivera <stefano@…>, 8 years ago

Overlay notes

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