source: nagslang/level.py@ 281:9b56e954c674

Last change on this file since 281:9b56e954c674 was 277:56e42c00da25, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Protagonist and enemies should see the world

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