source: nagslang/screens/area.py@ 686:ffac68f1c5ce

bugfixes
Last change on this file since 686:ffac68f1c5ce 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
RevLine 
[18]1"""Display a game area."""
2
[20]3import pygame
[21]4import pymunk
5import pymunk.pygame_util
[20]6
[555]7from nagslang.resources import resources
8from nagslang.mutators import ImageCentre, scaler
[480]9from nagslang.options import options
[301]10from nagslang.constants import (
[319]11 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS,
[336]12 COLLISION_TYPE_FURNITURE, COLLISION_TYPE_WEREWOLF_ATTACK,
[634]13 CMD_TOGGLE_FORM, CMD_ACTION, PROTAGONIST_HEALTH_MAX_LEVEL)
[520]14from nagslang.events import (
15 AddDrawableEvent, DeathEvent, DoorEvent, QuitEvent, ScreenChange)
[647]16from nagslang.game_object import SplashImage
[50]17from nagslang.level import Level
[65]18from nagslang.screens.base import Screen
[269]19from nagslang.sound import sound
[18]20
[83]21
[34]22class ControlKeys(object):
[100]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
[371]30 attack_keys = set([pygame.locals.K_z, pygame.locals.K_LCTRL])
31
[336]32 command_keys = {
33 pygame.locals.K_c: CMD_TOGGLE_FORM,
34 pygame.locals.K_SPACE: CMD_ACTION,
35 }
36
[34]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
[100]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
[371]60 def is_attacking(self):
61 return bool(self.keys_down & self.attack_keys)
62
[336]63 def get_command_key(self, key):
64 return self.command_keys.get(key, None)
65
[34]66
[107]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
[18]85class AreaScreen(Screen):
[21]86
[37]87 def setup(self):
[190]88 self._disable_render = False # Avoid redrawing on scene changes
[34]89 self.keys = ControlKeys()
[277]90 self._level = Level(self.name, self.world)
[145]91 self._level.load(self.space)
[107]92 self._drawables = Drawables()
[37]93 self.add_walls()
[188]94 self._add_collision_handlers()
[276]95 self.add_protagonist()
[145]96 self.add_game_objects()
[505]97 self.save_progress()
[608]98 sound.play_music(self._level.music, self._level.music_volume)
[511]99 self._background = None
100 self._surface = None
[21]101
[272]102 def teardown(self):
103 sound.stop()
[656]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)
[272]111
[321]112 @classmethod
113 def list_areas(self):
114 return Level.list_levels()
115
[319]116 def _player_collision_pre_solve_handler(self, space, arbiter):
[188]117 gobj = arbiter.shapes[1].physicser.game_object
[256]118 result = gobj.collide_with_protagonist(self.protagonist)
[192]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`.
[333]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
[188]129
[319]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
[188]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,
[319]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)
[333]144 self.space.add_collision_handler(
145 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
146 pre_solve=self._claw_attack_collision_pre_solve_handler)
[188]147
[37]148 def add_walls(self):
[21]149 self.walls = []
150 body = pymunk.Body()
[84]151 body.position = (0, 0)
[53]152 walls = self._level.get_walls()
153 for wall in walls:
[279]154 if len(wall) < 2:
155 # Don't try to add a useless wall
156 continue
[53]157 corners = wall
158 corner = corners[-1]
159 for next_corner in corners:
160 wall = pymunk.Segment(body, corner, next_corner, 5)
[301]161 wall.collision_type = COLLISION_TYPE_WALL
[53]162 wall.elasticity = 1.0
163 self.walls.append(wall)
164 corner = next_corner
[21]165 self.space.add(*self.walls)
166
[145]167 def add_game_objects(self):
[191]168 for drawable in self._level.drawables:
[145]169 self._drawables.add(drawable)
170
[37]171 def add_protagonist(self):
[276]172 self.protagonist = self.world.protagonist
[626]173 self.protagonist.reset()
[276]174 self.protagonist.change_space(self.space)
[505]175 self.world.rooms += 1
[107]176 self._drawables.add(self.protagonist)
[21]177
[505]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
[18]185 def handle_event(self, ev):
[20]186 if ev.type == pygame.locals.KEYDOWN:
187 if ev.key == pygame.locals.K_ESCAPE:
[480]188 if options.debug:
189 print ('Died at: (%i,%i)'
190 % (self.protagonist.physicser.position.x,
191 self.protagonist.physicser.position.y))
[437]192 if self._level.is_starting_level():
193 QuitEvent.post()
194 return
[440]195 self.protagonist.die()
[437]196 return
[336]197 cmd_key = self.keys.get_command_key(ev.key)
198 if cmd_key is not None:
199 self.protagonist.handle_keypress(cmd_key)
[180]200 elif DoorEvent.matches(ev):
201 self.protagonist.set_position(ev.dest_pos)
[471]202 if ev.destination is not None and ev.destination != self.name:
[512]203 if options.debug:
204 print 'Teleporting to %s' % ev.destination
[180]205 # Go to anther screen
[190]206 self._disable_render = True
[276]207 ScreenChange.post(ev.destination)
[190]208 return
[180]209 # else we're teleporting within the screen, and just the
210 # position change is enough
[440]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)
[520]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)
[34]222 self.keys.handle_event(ev)
[18]223
[87]224 def _calc_viewport(self, level_surface, display_surface):
225 level_size = level_surface.get_size()
226 display_size = display_surface.get_size()
[93]227 protagnist_pos = self.protagonist.physicser.get_render_position(
[127]228 level_surface)
[87]229 x_wide = display_size[0] // 2
230 y_wide = display_size[1] // 2
[127]231 if display_size[0] > level_size[0]:
232 x = -(display_size[0] - level_size[0]) // 2
233 elif protagnist_pos[0] < x_wide:
[87]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
[127]239 if display_size[1] > level_size[1]:
240 y = -(display_size[1] - level_size[1]) // 2
241 elif protagnist_pos[1] < y_wide:
[87]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
[18]249 def render(self, surface):
[190]250 if self._disable_render:
251 return
[511]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)
[105]260 for drawable in self._drawables:
[511]261 drawable.render(self._surface)
262 surface.blit(self._surface, (0, 0), render_rect)
[396]263 # Maximum width we allow for overlays
[511]264 max_width = min(render_rect.width, self._surface.get_width())
[520]265 for overlay in reversed(self._level.overlay_drawables):
[191]266 if overlay.is_visible():
[396]267 overlay.render(surface, render_rect.topleft, max_width)
[520]268 break
[243]269 self.render_health_bar(surface)
[555]270 self.render_inventory(surface)
[34]271
272 def tick_protagonist(self):
[100]273 dx, dy = self.keys.get_direction()
[47]274 self.protagonist.set_direction(dx, dy)
[371]275 if self.keys.is_attacking():
[393]276 self._handle_result(self.protagonist.handle_attack_key_down())
[34]277
278 def tick(self, seconds):
[303]279 super(AreaScreen, self).tick(seconds)
[34]280 self.tick_protagonist()
[143]281 for drawable in self._drawables:
[393]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)
[520]288 if drawable.overlay:
289 self._level.overlay_drawables.add(drawable.overlay)
[393]290 for drawable in result.remove:
291 self._drawables.remove(drawable)
[520]292 if drawable.overlay:
293 self._level.overlay_drawables.remove(drawable.overlay)
[243]294
[258]295 def render_health_bar(self, surface, damage_experienced=None):
[555]296 bar_surface = pygame.Surface((110, 40)).convert(surface)
[258]297 if damage_experienced:
298 health_box_colour = pygame.color.THECOLORS['red']
299 else:
300 health_box_colour = pygame.color.THECOLORS['white']
[347]301 bar_surface.fill(health_box_colour)
[246]302 if self.protagonist.in_human_form():
[243]303 health_colour = pygame.color.THECOLORS['red']
304 else:
[340]305 health_colour = pygame.color.THECOLORS['violetred3']
[634]306 health = self.protagonist.get_health_level()
307 rect = pygame.Rect(
308 5, 5, (100 * health) / PROTAGONIST_HEALTH_MAX_LEVEL, 30)
[347]309 pygame.draw.rect(bar_surface, health_colour, rect, 0)
310 bar_surface.set_alpha(192)
[365]311 y_pos = surface.get_height() - 20 - bar_surface.get_height()
312 surface.blit(bar_surface, (20, y_pos))
[555]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))
[647]336
337 def splash(self):
[650]338 AddDrawableEvent.post(SplashImage(resources.get_image('title.png'), 5))
Note: See TracBrowser for help on using the repository browser.