source: nagslang/level.py

Last change on this file was 608:9b9d529ba5d9, checked in by Simon Cross <hodgestar@…>, 8 years ago

Allow music volume to be specified.

File size: 9.4 KB
RevLine 
[408]1import os
2
[50]3import pygame
4import pygame.locals as pgl
[488]5import pymunk
[50]6
[378]7from nagslang import collectable
[145]8from nagslang import game_object as go
[168]9from nagslang import enemies
[201]10from nagslang import puzzle
[488]11from nagslang.utils import (
12 tile_surface, points_to_pygame, extend_line, points_to_lines)
[50]13from nagslang.resources import resources
[139]14from nagslang.yamlish import load, dump
[608]15from nagslang.constants import DEFAULT_MUSIC_VOLUME
[50]16
17POLY_COLORS = {
[53]18 1: pygame.color.THECOLORS['red'],
19 2: pygame.color.THECOLORS['green'],
20 3: pygame.color.THECOLORS['yellow'],
21 4: pygame.color.THECOLORS['blue'],
22 5: pygame.color.THECOLORS['lightblue'],
23 6: pygame.color.THECOLORS['magenta'],
[425]24 7: pygame.color.THECOLORS['lightgreen'],
25 8: pygame.color.THECOLORS['grey'],
[53]26}
[50]27
28
[197]29LINE_COLOR = pygame.color.THECOLORS['orange']
30
31
[50]32class Level(object):
[437]33 _game_starting_point = None
[50]34
[277]35 def __init__(self, name, world):
[50]36 self.name = name
37 # defaults
38 self.x = 800
39 self.y = 600
40 self.polygons = {}
[197]41 self.lines = []
[277]42 self.world = world
[346]43 self.world.level_state.setdefault(name, {})
[50]44 self.basetile = 'tiles/floor.png'
[582]45 self.music = None
[608]46 self.music_volume = None
[50]47 self._tile_image = None
48 self._surface = None
[431]49 self._base_surface = None
[95]50 self._exterior = False
[201]51 self._glue = puzzle.PuzzleGlue()
[191]52 self.drawables = []
53 self.overlay_drawables = []
[164]54 self._game_objects = []
[168]55 self._enemies = []
[50]56
[145]57 def _get_data(self):
58 # For overriding in tests.
[75]59 with resources.get_file('levels', self.name) as f:
[145]60 return load(f)
61
[164]62 def _dump_data(self, f):
63 # For manipulation in tests.
64 dump({
65 'size': [self.x, self.y],
66 'base_tile': self.basetile,
67 'polygons': self.polygons,
[197]68 'lines': self.lines,
[582]69 'music': self.music,
[608]70 'music_volume': self.music_volume,
[164]71 'game_objects': self._game_objects,
[168]72 'enemies': self._enemies,
[164]73 }, f)
74
[321]75 @classmethod
76 def list_levels(cls):
[408]77 dir_ = resources.get_resource_path('levels')
78 for file_ in os.listdir(dir_):
79 if file_ == 'meta':
80 continue
81 yield file_
82
83 @classmethod
84 def game_starting_point(cls):
[437]85 if not cls._game_starting_point:
86 with resources.get_file('levels', 'meta') as f:
87 data = load(f)
88 cls._game_starting_point = (data['starting_level'],
89 tuple(data['starting_position']))
90 return cls._game_starting_point
91
92 def is_starting_level(self):
93 return self.name == self.game_starting_point()[0]
[321]94
[145]95 def load(self, space):
96 data = self._get_data()
[139]97 self.x, self.y = data['size']
[317]98 self.basetile = data['base_tile']
[582]99 self.music = data['music']
[608]100 self.music_volume = data.get('music_volume', DEFAULT_MUSIC_VOLUME)
[139]101 for i, points in data['polygons'].iteritems():
102 self.polygons[i] = []
103 for point in points:
104 self.polygons[i].append(tuple(point))
[197]105 self.lines = data.get('lines', [])
[164]106 self._game_objects = data.get('game_objects', [])
107 for game_object_dict in self._game_objects:
[145]108 self._create_game_object(space, **game_object_dict)
[168]109 self._enemies = data.get('enemies', [])
110 for enemy_dict in self._enemies:
111 self._create_enemy(space, **enemy_dict)
[145]112
113 def _create_game_object(self, space, classname, args, name=None):
[209]114 modules = {
[378]115 'collectable': collectable,
[209]116 'game_object': go,
117 'puzzle': puzzle,
118 }
119 if '.' in classname:
120 module, classname = classname.split('.')
121 else:
122 module = 'game_object'
123 cls = getattr(modules[module], classname)
124
[379]125 if module == 'collectable' and name in self.world.inventory:
126 return
127
[201]128 if issubclass(cls, puzzle.Puzzler):
[145]129 gobj = cls(*args)
130 elif issubclass(cls, go.GameObject):
131 gobj = cls(space, *args)
[346]132 level_state = self.world.level_state[self.name]
133 stored_state = level_state.get(name, {})
134 should_save = bool(gobj.set_stored_state_dict(stored_state))
135 if should_save:
136 if name is None:
137 raise Exception(
138 "Unnamed game object wants to save state:" % (gobj,))
139 level_state[name] = stored_state
[191]140 self.drawables.append(gobj)
141 if gobj.overlay:
142 self.overlay_drawables.append(gobj.overlay)
[145]143 else:
144 raise TypeError(
145 "Expected a subclass of Puzzler or GameObject, got %s" % (
146 classname))
147 if name is not None:
148 self._glue.add_component(name, gobj)
[274]149 return gobj
[50]150
[168]151 def _create_enemy(self, space, classname, args, name=None):
152 cls = getattr(enemies, classname)
153 if issubclass(cls, go.GameObject):
[277]154 gobj = cls(space, self.world, *args)
[191]155 self.drawables.append(gobj)
[168]156 else:
157 raise TypeError(
158 "Expected a subclass of GameObject, got %s" % (
159 classname))
160 if name is not None:
161 self._glue.add_component(name, gobj)
[274]162 return gobj
[168]163
[95]164 def all_closed(self):
165 """Check if all the polygons are closed"""
[72]166 closed = True
[122]167 messages = []
168 for index, poly in self.polygons.items():
[72]169 if len(poly) == 0:
170 # We ignore empty polygons
171 continue
172 elif len(poly) == 1:
173 closed = False
[122]174 messages.append("Error: polygon %s too small" % index)
[72]175 elif poly[-1] != poly[0]:
176 closed = False
[122]177 messages.append("Error: polygon %s not closed" % index)
178 return closed, messages
[95]179
180 def save(self):
[122]181 closed, _ = self.all_closed()
[72]182 if not closed:
[122]183 return False
[75]184 with resources.get_file('levels', self.name, mode='w') as f:
[164]185 self._dump_data(f)
[122]186 return True
[72]187
[50]188 def get_size(self):
189 return self.x, self.y
190
191 def set_base_tile(self, new_tile):
192 self.basetile = new_tile
193 self._tile_image = None
194
195 def get_walls(self):
[197]196 walls = self.polygons.values()
197 walls.extend(self.lines)
198 return walls
[50]199
[488]200 def _draw_wall_line(self, points, width, colour, extend):
201 for line in points_to_lines(points):
202 if extend:
203 line = extend_line(
204 pymunk.Vec2d(line[0]), pymunk.Vec2d(line[1]), extend)
205 line = points_to_pygame(self._surface, line)
206 pygame.draw.line(self._surface, colour, line[0], line[1], width)
207
208 def _draw_walls_lines(self, width, colour, extend):
[50]209 for index, polygon in self.polygons.items():
[488]210 self._draw_wall_line(polygon, width, colour, extend)
[197]211 for line in self.lines:
[488]212 self._draw_wall_line(line, width, colour, extend)
213
214 def _draw_walls(self):
215 inner_colour = pygame.color.THECOLORS['red']
216 mid_colour = pygame.color.THECOLORS['orange']
217 outer_colour = pygame.color.THECOLORS['yellow']
218 self._draw_walls_lines(5, outer_colour, 0)
219 self._draw_walls_lines(3, outer_colour, 1)
220 self._draw_walls_lines(3, mid_colour, 0)
221 self._draw_walls_lines(1, inner_colour, 0)
[50]222
223 def get_background(self):
[485]224 if self._surface is None:
225 self._draw_background()
226 self._draw_exterior()
227 # Draw polygons
228 self._draw_walls()
[50]229 return self._surface
230
[95]231 def _draw_exterior(self, force=False):
232 """Fill the exterior of the level with black"""
233 if self._exterior and not force:
234 return
[118]235 white = pygame.color.THECOLORS['white']
236 black = pygame.color.THECOLORS['black']
[95]237 surface = pygame.surface.Surface((self.x, self.y), pgl.SRCALPHA)
[118]238 surface.fill(black)
[95]239 for index, polygon in self.polygons.items():
240 if len(polygon) > 1:
[488]241 pointlist = points_to_pygame(self._surface, polygon)
[95]242 # filled polygons
[118]243 color = white
244 # If a polygon overlaps on of the existing polygons,
245 # it is treated as negative
246 # This is not a complete inversion, since any overlap
247 # triggers this (inversion is easy enough, but the
248 # behaviour doesn't seem useful)
249 # We also only check the vertexes - not breaking this
250 # assumption is left to the level designers
251 surface.lock()
252 for p in pointlist:
253 if surface.get_at(p) == white:
254 color = black
255 surface.unlock()
256 pygame.draw.polygon(surface, color, pointlist, 0)
[95]257 self._surface.blit(surface, (0, 0), special_flags=pgl.BLEND_RGBA_MULT)
258 self._exterior = True
259
[50]260 def _draw_background(self, force=False):
261 if self._tile_image is None:
262 self._tile_image = resources.get_image(self.basetile)
263 if self._surface is not None and not force:
264 # We assume we don't change
265 return self._surface
[431]266 if self._base_surface is None:
[433]267 self._base_surface = tile_surface((self.x, self.y),
268 self._tile_image)
[431]269 self._surface = self._base_surface.copy()
[50]270 return self._surface
Note: See TracBrowser for help on using the repository browser.