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