source: nagslang/level.py@ 201:3495a2025bc6

Last change on this file since 201:3495a2025bc6 was 201:3495a2025bc6, checked in by Stefano Rivera <stefano@…>, 8 years ago

Break puzzlers out of game_object.py

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