source: nagslang/screens/area.py@ 391:866cdc74b26a

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

Use Result to handle enemy death (but keep the event for accounting purposes)

File size: 9.6 KB
RevLine 
[18]1"""Display a game area."""
2
[20]3import pygame
[21]4import pymunk
5import pymunk.pygame_util
[20]6
[301]7from nagslang.constants import (
[319]8 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS,
[336]9 COLLISION_TYPE_FURNITURE, COLLISION_TYPE_WEREWOLF_ATTACK,
[371]10 CMD_TOGGLE_FORM, CMD_ACTION)
[333]11from nagslang.events import (
[391]12 ScreenChange, DoorEvent, EnemyDeathEvent, FireEvent, ClawEvent)
[50]13from nagslang.level import Level
[65]14from nagslang.screens.base import Screen
[312]15from nagslang.game_object import Bullet, ClawAttack
[269]16from nagslang.sound import sound
[18]17
[83]18
[34]19class ControlKeys(object):
[100]20 direction_keys = {
21 (0, 1): set([pygame.locals.K_UP, pygame.locals.K_w]),
22 (0, -1): set([pygame.locals.K_DOWN, pygame.locals.K_s]),
23 (-1, 0): set([pygame.locals.K_LEFT, pygame.locals.K_a]),
24 (1, 0): set([pygame.locals.K_RIGHT, pygame.locals.K_d]),
25 }
26
[371]27 attack_keys = set([pygame.locals.K_z, pygame.locals.K_LCTRL])
28
[336]29 command_keys = {
30 pygame.locals.K_c: CMD_TOGGLE_FORM,
31 pygame.locals.K_SPACE: CMD_ACTION,
32 }
33
[34]34 def __init__(self):
35 self.keys_down = set()
36
37 def key_down(self, key):
38 self.keys_down.add(key)
39
40 def key_up(self, key):
41 self.keys_down.discard(key)
42
43 def handle_event(self, ev):
44 if ev.type == pygame.locals.KEYDOWN:
45 self.key_down(ev.key)
46 elif ev.type == pygame.locals.KEYUP:
47 self.key_up(ev.key)
48
[100]49 def get_direction(self):
50 dx, dy = 0, 0
51 for (tx, ty), keys in self.direction_keys.iteritems():
52 if self.keys_down & keys:
53 dx += tx
54 dy += ty
55 return (dx, dy)
56
[371]57 def is_attacking(self):
58 return bool(self.keys_down & self.attack_keys)
59
[336]60 def get_command_key(self, key):
61 return self.command_keys.get(key, None)
62
[34]63
[107]64class Drawables(object):
65 def __init__(self):
66 self._drawables = {}
67
68 def add(self, drawable):
69 self._drawables.setdefault(drawable.zorder, []).append(drawable)
70
71 def remove(self, drawable):
72 self._drawables[drawable.zorder].remove(drawable)
73
74 def get_drawables(self):
75 for zorder in sorted(self._drawables):
76 for drawable in self._drawables[zorder]:
77 yield drawable
78
79 __iter__ = get_drawables
80
81
[18]82class AreaScreen(Screen):
[21]83
[37]84 def setup(self):
[190]85 self._disable_render = False # Avoid redrawing on scene changes
[34]86 self.keys = ControlKeys()
[277]87 self._level = Level(self.name, self.world)
[145]88 self._level.load(self.space)
[107]89 self._drawables = Drawables()
[37]90 self.add_walls()
[188]91 self._add_collision_handlers()
[276]92 self.add_protagonist()
[145]93 self.add_game_objects()
[269]94 sound.play_music("POL-cyber-factory-short.ogg")
[21]95
[272]96 def teardown(self):
97 sound.stop()
98
[321]99 @classmethod
100 def list_areas(self):
101 return Level.list_levels()
102
[319]103 def _player_collision_pre_solve_handler(self, space, arbiter):
[188]104 gobj = arbiter.shapes[1].physicser.game_object
[256]105 result = gobj.collide_with_protagonist(self.protagonist)
[192]106 # The collision handler must return `True` or `False`. We don't want to
107 # accidentally reject collisions from handlers that return `None`, so
108 # we explicitly check for `False` and treate everything else as `True`.
[333]109 return result is not False
110
111 def _claw_attack_collision_pre_solve_handler(self, space, arbiter):
112 claw = arbiter.shapes[0].physicser.game_object
113 gobj = arbiter.shapes[1].physicser.game_object
114 result = gobj.collide_with_claw_attack(claw)
115 return result is not False
[188]116
[319]117 def _furniture_collision_pre_solve_handler(self, space, arbiter):
118 furniture = arbiter.shapes[0].physicser.game_object
119 gobj = arbiter.shapes[1].physicser.game_object
120 result = gobj.collide_with_furniture(furniture)
121 return result is not False
122
[188]123 def _add_collision_handlers(self):
124 for collision_type in CALLBACK_COLLIDERS:
125 self.space.add_collision_handler(
126 COLLISION_TYPE_PLAYER, collision_type,
[319]127 pre_solve=self._player_collision_pre_solve_handler)
128 self.space.add_collision_handler(
129 COLLISION_TYPE_FURNITURE, collision_type,
130 pre_solve=self._furniture_collision_pre_solve_handler)
[333]131 self.space.add_collision_handler(
132 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
133 pre_solve=self._claw_attack_collision_pre_solve_handler)
[188]134
[37]135 def add_walls(self):
[21]136 self.walls = []
137 body = pymunk.Body()
[84]138 body.position = (0, 0)
[53]139 walls = self._level.get_walls()
140 for wall in walls:
[279]141 if len(wall) < 2:
142 # Don't try to add a useless wall
143 continue
[53]144 corners = wall
145 corner = corners[-1]
146 for next_corner in corners:
147 wall = pymunk.Segment(body, corner, next_corner, 5)
[301]148 wall.collision_type = COLLISION_TYPE_WALL
[53]149 wall.elasticity = 1.0
150 self.walls.append(wall)
151 corner = next_corner
[21]152 self.space.add(*self.walls)
153
[145]154 def add_game_objects(self):
[191]155 for drawable in self._level.drawables:
[145]156 self._drawables.add(drawable)
157
[37]158 def add_protagonist(self):
[276]159 self.protagonist = self.world.protagonist
160 self.protagonist.change_space(self.space)
[107]161 self._drawables.add(self.protagonist)
[21]162
[18]163 def handle_event(self, ev):
[20]164 if ev.type == pygame.locals.KEYDOWN:
165 if ev.key == pygame.locals.K_ESCAPE:
166 ScreenChange.post('menu')
[336]167 cmd_key = self.keys.get_command_key(ev.key)
168 if cmd_key is not None:
169 self.protagonist.handle_keypress(cmd_key)
[180]170 elif DoorEvent.matches(ev):
171 self.protagonist.set_position(ev.dest_pos)
172 if ev.destination != self.name:
173 # Go to anther screen
[190]174 self._disable_render = True
[238]175 self.world.rooms += 1
[345]176 self.world.level = (ev.destination, ev.dest_pos)
[276]177 ScreenChange.post(ev.destination)
[190]178 return
[180]179 # else we're teleporting within the screen, and just the
180 # position change is enough
[261]181 elif FireEvent.matches(ev):
[305]182 bullet = Bullet(self.space, ev.source, ev.impulse, ev.damage,
[363]183 ev.bullet_type, ev.source_collision_type)
[261]184 self._drawables.add(bullet)
[308]185 elif EnemyDeathEvent.matches(ev):
186 self.world.kills += 1
[312]187 elif ClawEvent.matches(ev):
188 claw_attack = ClawAttack(self.space, ev.source, ev.vector,
[333]189 ev.damage)
[312]190 self._drawables.add(claw_attack)
[34]191 self.keys.handle_event(ev)
[18]192
[87]193 def _calc_viewport(self, level_surface, display_surface):
194 level_size = level_surface.get_size()
195 display_size = display_surface.get_size()
[93]196 protagnist_pos = self.protagonist.physicser.get_render_position(
[127]197 level_surface)
[87]198 x_wide = display_size[0] // 2
199 y_wide = display_size[1] // 2
[127]200 if display_size[0] > level_size[0]:
201 x = -(display_size[0] - level_size[0]) // 2
202 elif protagnist_pos[0] < x_wide:
[87]203 x = 0
204 elif protagnist_pos[0] > level_size[0] - x_wide:
205 x = level_size[0] - display_size[0]
206 else:
207 x = protagnist_pos[0] - x_wide
[127]208 if display_size[1] > level_size[1]:
209 y = -(display_size[1] - level_size[1]) // 2
210 elif protagnist_pos[1] < y_wide:
[87]211 y = 0
212 elif protagnist_pos[1] > level_size[1] - y_wide:
213 y = level_size[1] - display_size[1]
214 else:
215 y = protagnist_pos[1] - y_wide
216 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
217
[18]218 def render(self, surface):
[190]219 if self._disable_render:
220 return
[50]221 background = self._level.get_background()
[84]222 mysurface = background.copy()
[105]223 for drawable in self._drawables:
224 drawable.render(mysurface)
[87]225 render_rect = self._calc_viewport(mysurface, surface)
226 surface.blit(mysurface, (0, 0), render_rect)
[191]227 for overlay in self._level.overlay_drawables:
228 if overlay.is_visible():
[211]229 overlay.render(surface, render_rect.topleft)
[243]230 self.render_health_bar(surface)
[34]231
232 def tick_protagonist(self):
[100]233 dx, dy = self.keys.get_direction()
[47]234 self.protagonist.set_direction(dx, dy)
[371]235 if self.keys.is_attacking():
236 self.protagonist.handle_attack_key_down()
[34]237
238 def tick(self, seconds):
[303]239 super(AreaScreen, self).tick(seconds)
[34]240 self.tick_protagonist()
[143]241 for drawable in self._drawables:
[385]242 result = drawable.update(seconds)
243 if result is not None:
244 for new_drawable in result.add:
245 self._drawables.add(new_drawable)
246 for old_drawable in result.remove:
247 self._drawables.remove(old_drawable)
[243]248
[258]249 def render_health_bar(self, surface, damage_experienced=None):
[347]250 bar_surface = pygame.Surface((110, 50)).convert(surface)
[258]251 if damage_experienced:
252 health_box_colour = pygame.color.THECOLORS['red']
253 else:
254 health_box_colour = pygame.color.THECOLORS['white']
[347]255 bar_surface.fill(health_box_colour)
[246]256 if self.protagonist.in_human_form():
[243]257 health_colour = pygame.color.THECOLORS['red']
258 else:
[340]259 health_colour = pygame.color.THECOLORS['violetred3']
[347]260 rect = pygame.Rect(5, 5, self.protagonist.get_health_level(), 40)
261 pygame.draw.rect(bar_surface, health_colour, rect, 0)
262 bar_surface.set_alpha(192)
[365]263 y_pos = surface.get_height() - 20 - bar_surface.get_height()
264 surface.blit(bar_surface, (20, y_pos))
Note: See TracBrowser for help on using the repository browser.