source: nagslang/level.py@ 190:97627a999042

Last change on this file since 190:97627a999042 was 168:ce8d4fc3baf4, checked in by Neil Muller <drnlmuller@…>, 8 years ago

A patrolling alien

File size: 6.9 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._game_objects = []
34 self._enemies = []
35
36 def _get_data(self):
37 # For overriding in tests.
38 with resources.get_file('levels', self.name) as f:
39 return load(f)
40
41 def _dump_data(self, f):
42 # For manipulation in tests.
43 dump({
44 'size': [self.x, self.y],
45 'base_tile': self.basetile,
46 'polygons': self.polygons,
47 'game_objects': self._game_objects,
48 'enemies': self._enemies,
49 }, f)
50
51 def load(self, space):
52 data = self._get_data()
53 self.x, self.y = data['size']
54 self.base_tile = data['base_tile']
55 for i, points in data['polygons'].iteritems():
56 self.polygons[i] = []
57 for point in points:
58 self.polygons[i].append(tuple(point))
59 self._game_objects = data.get('game_objects', [])
60 for game_object_dict in self._game_objects:
61 self._create_game_object(space, **game_object_dict)
62 self._enemies = data.get('enemies', [])
63 for enemy_dict in self._enemies:
64 self._create_enemy(space, **enemy_dict)
65
66 def _create_game_object(self, space, classname, args, name=None):
67 # We should probably build a registry of game objects or something.
68 # At least this is better than just calling `eval`, right?
69 cls = getattr(go, classname)
70 if issubclass(cls, go.Puzzler):
71 gobj = cls(*args)
72 elif issubclass(cls, go.GameObject):
73 gobj = cls(space, *args)
74 self._drawables.append(gobj)
75 else:
76 raise TypeError(
77 "Expected a subclass of Puzzler or GameObject, got %s" % (
78 classname))
79 if name is not None:
80 self._glue.add_component(name, gobj)
81
82 def _create_enemy(self, space, classname, args, name=None):
83 cls = getattr(enemies, classname)
84 if issubclass(cls, go.GameObject):
85 gobj = cls(space, *args)
86 self._drawables.append(gobj)
87 else:
88 raise TypeError(
89 "Expected a subclass of GameObject, got %s" % (
90 classname))
91 if name is not None:
92 self._glue.add_component(name, gobj)
93
94 def all_closed(self):
95 """Check if all the polygons are closed"""
96 closed = True
97 messages = []
98 for index, poly in self.polygons.items():
99 if len(poly) == 0:
100 # We ignore empty polygons
101 continue
102 elif len(poly) == 1:
103 closed = False
104 messages.append("Error: polygon %s too small" % index)
105 elif poly[-1] != poly[0]:
106 closed = False
107 messages.append("Error: polygon %s not closed" % index)
108 return closed, messages
109
110 def save(self):
111 closed, _ = self.all_closed()
112 if not closed:
113 return False
114 with resources.get_file('levels', self.name, mode='w') as f:
115 self._dump_data(f)
116 return True
117
118 def get_size(self):
119 return self.x, self.y
120
121 def set_base_tile(self, new_tile):
122 self.basetile = new_tile
123 self._tile_image = None
124
125 def point_to_pygame(self, pos):
126 # Convert a point from pymunk (which is what we store)
127 # to pygame for drawing
128 return (pos[0], self.y - pos[1])
129
130 def get_walls(self):
131 return self.polygons.values()
132
133 def get_drawables(self):
134 return self._drawables
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.