source: nagslang/screens/area.py@ 656:2d408092bbae

bugfixes
Last change on this file since 656:2d408092bbae was 656:2d408092bbae, checked in by Neil Muller <drnlmuller@…>, 8 years ago

Cleanup collision handlers when we're done with the space

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