source: nagslang/level.py@ 197:34c11bb5c96e

Last change on this file since 197:34c11bb5c96e was 197:34c11bb5c96e, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Interior walls.

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