source: nagslang/level.py@ 202:63d7ab8ede83

Last change on this file since 202:63d7ab8ede83 was 201:3495a2025bc6, checked in by Stefano Rivera <stefano@…>, 8 years ago

Break puzzlers out of game_object.py

File size: 7.4 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):
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 # We should probably build a registry of game objects or something.
76 # At least this is better than just calling `eval`, right?
77 cls = getattr(go, classname)
78 if issubclass(cls, puzzle.Puzzler):
79 gobj = cls(*args)
80 elif issubclass(cls, go.GameObject):
81 gobj = cls(space, *args)
82 self.drawables.append(gobj)
83 if gobj.overlay:
84 self.overlay_drawables.append(gobj.overlay)
85 else:
86 raise TypeError(
87 "Expected a subclass of Puzzler or GameObject, got %s" % (
88 classname))
89 if name is not None:
90 self._glue.add_component(name, gobj)
91
92 def _create_enemy(self, space, classname, args, name=None):
93 cls = getattr(enemies, classname)
94 if issubclass(cls, go.GameObject):
95 gobj = cls(space, *args)
96 self.drawables.append(gobj)
97 else:
98 raise TypeError(
99 "Expected a subclass of GameObject, got %s" % (
100 classname))
101 if name is not None:
102 self._glue.add_component(name, gobj)
103
104 def all_closed(self):
105 """Check if all the polygons are closed"""
106 closed = True
107 messages = []
108 for index, poly in self.polygons.items():
109 if len(poly) == 0:
110 # We ignore empty polygons
111 continue
112 elif len(poly) == 1:
113 closed = False
114 messages.append("Error: polygon %s too small" % index)
115 elif poly[-1] != poly[0]:
116 closed = False
117 messages.append("Error: polygon %s not closed" % index)
118 return closed, messages
119
120 def save(self):
121 closed, _ = self.all_closed()
122 if not closed:
123 return False
124 with resources.get_file('levels', self.name, mode='w') as f:
125 self._dump_data(f)
126 return True
127
128 def get_size(self):
129 return self.x, self.y
130
131 def set_base_tile(self, new_tile):
132 self.basetile = new_tile
133 self._tile_image = None
134
135 def point_to_pygame(self, pos):
136 # Convert a point from pymunk (which is what we store)
137 # to pygame for drawing
138 return (pos[0], self.y - pos[1])
139
140 def get_walls(self):
141 walls = self.polygons.values()
142 walls.extend(self.lines)
143 return walls
144
145 def _draw_walls(self):
146 for index, polygon in self.polygons.items():
147 color = POLY_COLORS[index]
148 if len(polygon) > 1:
149 pointlist = [self.point_to_pygame(p) for p in polygon]
150 pygame.draw.lines(self._surface, color, False, pointlist, 2)
151 for line in self.lines:
152 pointlist = [self.point_to_pygame(p) for p in line]
153 pygame.draw.lines(self._surface, LINE_COLOR, False, pointlist, 2)
154
155 def get_background(self):
156 self._draw_background()
157 self._draw_exterior()
158 # Draw polygons
159 self._draw_walls()
160 return self._surface
161
162 def _draw_exterior(self, force=False):
163 """Fill the exterior of the level with black"""
164 if self._exterior and not force:
165 return
166 white = pygame.color.THECOLORS['white']
167 black = pygame.color.THECOLORS['black']
168 surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
169 surface.fill(black)
170 for index, polygon in self.polygons.items():
171 if len(polygon) > 1:
172 pointlist = [self.point_to_pygame(p) for p in polygon]
173 # filled polygons
174 color = white
175 # If a polygon overlaps on of the existing polygons,
176 # it is treated as negative
177 # This is not a complete inversion, since any overlap
178 # triggers this (inversion is easy enough, but the
179 # behaviour doesn't seem useful)
180 # We also only check the vertexes - not breaking this
181 # assumption is left to the level designers
182 surface.lock()
183 for p in pointlist:
184 if surface.get_at(p) == white:
185 color = black
186 surface.unlock()
187 pygame.draw.polygon(surface, color, pointlist, 0)
188 self._surface.blit(surface, (0, 0), special_flags=pgl.BLEND_RGBA_MULT)
189 self._exterior = True
190
191 def _draw_background(self, force=False):
192 if self._tile_image is None:
193 self._tile_image = resources.get_image(self.basetile)
194 if self._surface is not None and not force:
195 # We assume we don't change
196 return self._surface
197 self._surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
198 self._surface.fill(pygame.color.THECOLORS['black'])
199 x_step = self._tile_image.get_rect().width
200 y_step = self._tile_image.get_rect().height
201 x_count = self.x // x_step + 1
202 y_count = self.y / y_step + 1
203 for x in range(x_count):
204 for y in range(y_count):
205 tile_rect = pygame.rect.Rect(x * x_step, y * y_step,
206 x_step, y_step)
207 self._surface.blit(self._tile_image, tile_rect)
208 return self._surface
Note: See TracBrowser for help on using the repository browser.