source: nagslang/level.py@ 293:47226c661ae2

Last change on this file since 293:47226c661ae2 was 277:56e42c00da25, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Protagonist and enemies should see the world

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