source: nagslang/level.py@ 98:93256a0987a2

Last change on this file since 98:93256a0987a2 was 98:93256a0987a2, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Fix newer pep8 continuation complaint

File size: 5.7 KB
Line 
1import pygame
2import pygame.locals as pgl
3
4from nagslang.resources import resources
5
6POLY_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
16class 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 for poly in self.polygons.values():
70 if len(poly) == 0:
71 # We ignore empty polygons
72 continue
73 elif len(poly) == 1:
74 closed = False
75 print "\033[31mError: polygon too small\033[0m"
76 elif poly[-1] != poly[0]:
77 closed = False
78 print "\033[31mError: polygon not closed\033[0m"
79 return closed
80
81 def save(self):
82 closed = self.all_closed()
83 if not closed:
84 print 'Not saving the level'
85 return
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 print 'level %s saved' % self.name
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 surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
132 surface.fill(pygame.color.THECOLORS["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 pygame.draw.polygon(surface, pygame.color.THECOLORS['white'],
138 pointlist, 0)
139 self._surface.blit(surface, (0, 0), special_flags=pgl.BLEND_RGBA_MULT)
140 self._exterior = True
141
142 def _draw_background(self, force=False):
143 if self._tile_image is None:
144 self._tile_image = resources.get_image(self.basetile)
145 if self._surface is not None and not force:
146 # We assume we don't change
147 return self._surface
148 self._surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
149 self._surface.fill(pygame.color.THECOLORS['black'])
150 x_step = self._tile_image.get_rect().width
151 y_step = self._tile_image.get_rect().height
152 x_count = self.x // x_step + 1
153 y_count = self.y / y_step + 1
154 for x in range(x_count):
155 for y in range(y_count):
156 tile_rect = pygame.rect.Rect(x * x_step, y * y_step,
157 x_step, y_step)
158 self._surface.blit(self._tile_image, tile_rect)
159 return self._surface
Note: See TracBrowser for help on using the repository browser.