source: nagslang/level.py@ 164:06c681ff53aa

Last change on this file since 164:06c681ff53aa was 164:06c681ff53aa, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Round-tripping through load/save shouldn't discard objects

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