source: nagslang/screens/area.py@ 586:dc4eeb8547dd

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

Play the level's configured sound

File size: 12.1 KB
Line 
1"""Display a game area."""
2
3import pygame
4import pymunk
5import pymunk.pygame_util
6
7from nagslang.resources import resources
8from nagslang.mutators import ImageCentre, scaler
9from nagslang.options import options
10from nagslang.constants import (
11 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS,
12 COLLISION_TYPE_FURNITURE, COLLISION_TYPE_WEREWOLF_ATTACK,
13 CMD_TOGGLE_FORM, CMD_ACTION)
14from nagslang.events import (
15 AddDrawableEvent, DeathEvent, DoorEvent, QuitEvent, ScreenChange)
16from nagslang.level import Level
17from nagslang.screens.base import Screen
18from nagslang.sound import sound
19
20
21class ControlKeys(object):
22 direction_keys = {
23 (0, 1): set([pygame.locals.K_UP, pygame.locals.K_w]),
24 (0, -1): set([pygame.locals.K_DOWN, pygame.locals.K_s]),
25 (-1, 0): set([pygame.locals.K_LEFT, pygame.locals.K_a]),
26 (1, 0): set([pygame.locals.K_RIGHT, pygame.locals.K_d]),
27 }
28
29 attack_keys = set([pygame.locals.K_z, pygame.locals.K_LCTRL])
30
31 command_keys = {
32 pygame.locals.K_c: CMD_TOGGLE_FORM,
33 pygame.locals.K_SPACE: CMD_ACTION,
34 }
35
36 def __init__(self):
37 self.keys_down = set()
38
39 def key_down(self, key):
40 self.keys_down.add(key)
41
42 def key_up(self, key):
43 self.keys_down.discard(key)
44
45 def handle_event(self, ev):
46 if ev.type == pygame.locals.KEYDOWN:
47 self.key_down(ev.key)
48 elif ev.type == pygame.locals.KEYUP:
49 self.key_up(ev.key)
50
51 def get_direction(self):
52 dx, dy = 0, 0
53 for (tx, ty), keys in self.direction_keys.iteritems():
54 if self.keys_down & keys:
55 dx += tx
56 dy += ty
57 return (dx, dy)
58
59 def is_attacking(self):
60 return bool(self.keys_down & self.attack_keys)
61
62 def get_command_key(self, key):
63 return self.command_keys.get(key, None)
64
65
66class Drawables(object):
67 def __init__(self):
68 self._drawables = {}
69
70 def add(self, drawable):
71 self._drawables.setdefault(drawable.zorder, []).append(drawable)
72
73 def remove(self, drawable):
74 self._drawables[drawable.zorder].remove(drawable)
75
76 def get_drawables(self):
77 for zorder in sorted(self._drawables):
78 for drawable in self._drawables[zorder]:
79 yield drawable
80
81 __iter__ = get_drawables
82
83
84class AreaScreen(Screen):
85
86 def setup(self):
87 self._disable_render = False # Avoid redrawing on scene changes
88 self.keys = ControlKeys()
89 self._level = Level(self.name, self.world)
90 self._level.load(self.space)
91 self._drawables = Drawables()
92 self.add_walls()
93 self._add_collision_handlers()
94 self.add_protagonist()
95 self.add_game_objects()
96 self.save_progress()
97 sound.play_music(self._level.music)
98 self._background = None
99 self._surface = None
100
101 def teardown(self):
102 sound.stop()
103
104 @classmethod
105 def list_areas(self):
106 return Level.list_levels()
107
108 def _player_collision_pre_solve_handler(self, space, arbiter):
109 gobj = arbiter.shapes[1].physicser.game_object
110 result = gobj.collide_with_protagonist(self.protagonist)
111 # The collision handler must return `True` or `False`. We don't want to
112 # accidentally reject collisions from handlers that return `None`, so
113 # we explicitly check for `False` and treate everything else as `True`.
114 return result is not False
115
116 def _claw_attack_collision_pre_solve_handler(self, space, arbiter):
117 claw = arbiter.shapes[0].physicser.game_object
118 gobj = arbiter.shapes[1].physicser.game_object
119 result = gobj.collide_with_claw_attack(claw)
120 return result is not False
121
122 def _furniture_collision_pre_solve_handler(self, space, arbiter):
123 furniture = arbiter.shapes[0].physicser.game_object
124 gobj = arbiter.shapes[1].physicser.game_object
125 result = gobj.collide_with_furniture(furniture)
126 return result is not False
127
128 def _add_collision_handlers(self):
129 for collision_type in CALLBACK_COLLIDERS:
130 self.space.add_collision_handler(
131 COLLISION_TYPE_PLAYER, collision_type,
132 pre_solve=self._player_collision_pre_solve_handler)
133 self.space.add_collision_handler(
134 COLLISION_TYPE_FURNITURE, collision_type,
135 pre_solve=self._furniture_collision_pre_solve_handler)
136 self.space.add_collision_handler(
137 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
138 pre_solve=self._claw_attack_collision_pre_solve_handler)
139
140 def add_walls(self):
141 self.walls = []
142 body = pymunk.Body()
143 body.position = (0, 0)
144 walls = self._level.get_walls()
145 for wall in walls:
146 if len(wall) < 2:
147 # Don't try to add a useless wall
148 continue
149 corners = wall
150 corner = corners[-1]
151 for next_corner in corners:
152 wall = pymunk.Segment(body, corner, next_corner, 5)
153 wall.collision_type = COLLISION_TYPE_WALL
154 wall.elasticity = 1.0
155 self.walls.append(wall)
156 corner = next_corner
157 self.space.add(*self.walls)
158
159 def add_game_objects(self):
160 for drawable in self._level.drawables:
161 self._drawables.add(drawable)
162
163 def add_protagonist(self):
164 self.protagonist = self.world.protagonist
165 self.protagonist.change_space(self.space)
166 self.world.rooms += 1
167 self._drawables.add(self.protagonist)
168
169 def save_progress(self):
170 if self.name == Level.game_starting_point()[0]:
171 return
172 self.world.level = (self.name, (self.protagonist.physicser.position.x,
173 self.protagonist.physicser.position.y))
174 self.world.save()
175
176 def handle_event(self, ev):
177 if ev.type == pygame.locals.KEYDOWN:
178 if ev.key == pygame.locals.K_ESCAPE:
179 if options.debug:
180 print ('Died at: (%i,%i)'
181 % (self.protagonist.physicser.position.x,
182 self.protagonist.physicser.position.y))
183 if self._level.is_starting_level():
184 QuitEvent.post()
185 return
186 self.protagonist.die()
187 return
188 cmd_key = self.keys.get_command_key(ev.key)
189 if cmd_key is not None:
190 self.protagonist.handle_keypress(cmd_key)
191 elif DoorEvent.matches(ev):
192 self.protagonist.set_position(ev.dest_pos)
193 if ev.destination is not None and ev.destination != self.name:
194 if options.debug:
195 print 'Teleporting to %s' % ev.destination
196 # Go to anther screen
197 self._disable_render = True
198 ScreenChange.post(ev.destination)
199 return
200 # else we're teleporting within the screen, and just the
201 # position change is enough
202 elif DeathEvent.matches(ev):
203 self._disable_render = True
204 self.world.load()
205 self.world.deaths += 1
206 level, pos = Level.game_starting_point()
207 self.protagonist.set_position(pos)
208 ScreenChange.post(level)
209 elif AddDrawableEvent.matches(ev):
210 self._drawables.add(ev.drawable)
211 if ev.drawable.overlay:
212 self._level.overlay_drawables.append(ev.drawable.overlay)
213 self.keys.handle_event(ev)
214
215 def _calc_viewport(self, level_surface, display_surface):
216 level_size = level_surface.get_size()
217 display_size = display_surface.get_size()
218 protagnist_pos = self.protagonist.physicser.get_render_position(
219 level_surface)
220 x_wide = display_size[0] // 2
221 y_wide = display_size[1] // 2
222 if display_size[0] > level_size[0]:
223 x = -(display_size[0] - level_size[0]) // 2
224 elif protagnist_pos[0] < x_wide:
225 x = 0
226 elif protagnist_pos[0] > level_size[0] - x_wide:
227 x = level_size[0] - display_size[0]
228 else:
229 x = protagnist_pos[0] - x_wide
230 if display_size[1] > level_size[1]:
231 y = -(display_size[1] - level_size[1]) // 2
232 elif protagnist_pos[1] < y_wide:
233 y = 0
234 elif protagnist_pos[1] > level_size[1] - y_wide:
235 y = level_size[1] - display_size[1]
236 else:
237 y = protagnist_pos[1] - y_wide
238 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
239
240 def render(self, surface):
241 if self._disable_render:
242 return
243 if self._background is None:
244 bg = self._level.get_background()
245 self._background = pygame.surface.Surface(bg.get_size())
246 self._background.blit(bg, (0, 0))
247 self._surface = pygame.surface.Surface(self._background.get_size())
248 render_rect = self._calc_viewport(self._surface, surface)
249 self._surface.set_clip(render_rect)
250 self._surface.blit(self._background, render_rect.topleft, render_rect)
251 for drawable in self._drawables:
252 drawable.render(self._surface)
253 surface.blit(self._surface, (0, 0), render_rect)
254 # Maximum width we allow for overlays
255 max_width = min(render_rect.width, self._surface.get_width())
256 for overlay in reversed(self._level.overlay_drawables):
257 if overlay.is_visible():
258 overlay.render(surface, render_rect.topleft, max_width)
259 break
260 self.render_health_bar(surface)
261 self.render_inventory(surface)
262
263 def tick_protagonist(self):
264 dx, dy = self.keys.get_direction()
265 self.protagonist.set_direction(dx, dy)
266 if self.keys.is_attacking():
267 self._handle_result(self.protagonist.handle_attack_key_down())
268
269 def tick(self, seconds):
270 super(AreaScreen, self).tick(seconds)
271 self.tick_protagonist()
272 for drawable in self._drawables:
273 self._handle_result(drawable.update(seconds))
274
275 def _handle_result(self, result):
276 if result is not None:
277 for drawable in result.add:
278 self._drawables.add(drawable)
279 if drawable.overlay:
280 self._level.overlay_drawables.add(drawable.overlay)
281 for drawable in result.remove:
282 self._drawables.remove(drawable)
283 if drawable.overlay:
284 self._level.overlay_drawables.remove(drawable.overlay)
285
286 def render_health_bar(self, surface, damage_experienced=None):
287 bar_surface = pygame.Surface((110, 40)).convert(surface)
288 if damage_experienced:
289 health_box_colour = pygame.color.THECOLORS['red']
290 else:
291 health_box_colour = pygame.color.THECOLORS['white']
292 bar_surface.fill(health_box_colour)
293 if self.protagonist.in_human_form():
294 health_colour = pygame.color.THECOLORS['red']
295 else:
296 health_colour = pygame.color.THECOLORS['violetred3']
297 rect = pygame.Rect(5, 5, self.protagonist.get_health_level(), 30)
298 pygame.draw.rect(bar_surface, health_colour, rect, 0)
299 bar_surface.set_alpha(192)
300 y_pos = surface.get_height() - 20 - bar_surface.get_height()
301 surface.blit(bar_surface, (20, y_pos))
302
303 def render_inventory(self, surface):
304 items = len(self.world.inventory)
305 if not items:
306 return
307 padding = 4
308 img_size = 64
309 size = 32
310 inv_surf = pygame.Surface(
311 (padding + (size + padding) * items,
312 (2 * padding + size)))
313 inv_surf = inv_surf.convert(surface)
314 inv_surf.set_alpha(192)
315 inv_surf.fill(pygame.color.THECOLORS['white'])
316 for index, item in enumerate(sorted(self.world.inventory)):
317 img = resources.get_image(
318 'objects', item + '.png',
319 transforms=(ImageCentre((img_size, img_size)),
320 scaler((size, size))))
321 inv_surf.blit(img, (padding + index * (size + padding), padding))
322 y_pos = surface.get_height() - 20 - inv_surf.get_height()
323 x_pos = 130 + padding
324 surface.blit(inv_surf, (x_pos, y_pos))
Note: See TracBrowser for help on using the repository browser.