source: nagslang/level.py@ 139:d1f543ff0805

Last change on this file since 139:d1f543ff0805 was 139:d1f543ff0805, checked in by Stefano Rivera <stefano@…>, 7 years ago

YAML levels

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