source: nagslang/level.py@ 155:b455873020be

Last change on this file since 155:b455873020be was 145:0c49627920eb, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Load game objects from level.

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