source: nagslang/screens/area.py@ 520:3f79a77ef1e3

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

Ephemeral messages

File size: 11.1 KB
RevLine 
[18]1"""Display a game area."""
2
[20]3import pygame
[21]4import pymunk
5import pymunk.pygame_util
[20]6
[480]7from nagslang.options import options
[301]8from nagslang.constants import (
[319]9 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS,
[336]10 COLLISION_TYPE_FURNITURE, COLLISION_TYPE_WEREWOLF_ATTACK,
[371]11 CMD_TOGGLE_FORM, CMD_ACTION)
[520]12from nagslang.events import (
13 AddDrawableEvent, DeathEvent, DoorEvent, QuitEvent, ScreenChange)
[50]14from nagslang.level import Level
[65]15from nagslang.screens.base import Screen
[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()
[505]94 self.save_progress()
[269]95 sound.play_music("POL-cyber-factory-short.ogg")
[511]96 self._background = None
97 self._surface = None
[21]98
[272]99 def teardown(self):
100 sound.stop()
101
[321]102 @classmethod
103 def list_areas(self):
104 return Level.list_levels()
105
[319]106 def _player_collision_pre_solve_handler(self, space, arbiter):
[188]107 gobj = arbiter.shapes[1].physicser.game_object
[256]108 result = gobj.collide_with_protagonist(self.protagonist)
[192]109 # The collision handler must return `True` or `False`. We don't want to
110 # accidentally reject collisions from handlers that return `None`, so
111 # we explicitly check for `False` and treate everything else as `True`.
[333]112 return result is not False
113
114 def _claw_attack_collision_pre_solve_handler(self, space, arbiter):
115 claw = arbiter.shapes[0].physicser.game_object
116 gobj = arbiter.shapes[1].physicser.game_object
117 result = gobj.collide_with_claw_attack(claw)
118 return result is not False
[188]119
[319]120 def _furniture_collision_pre_solve_handler(self, space, arbiter):
121 furniture = arbiter.shapes[0].physicser.game_object
122 gobj = arbiter.shapes[1].physicser.game_object
123 result = gobj.collide_with_furniture(furniture)
124 return result is not False
125
[188]126 def _add_collision_handlers(self):
127 for collision_type in CALLBACK_COLLIDERS:
128 self.space.add_collision_handler(
129 COLLISION_TYPE_PLAYER, collision_type,
[319]130 pre_solve=self._player_collision_pre_solve_handler)
131 self.space.add_collision_handler(
132 COLLISION_TYPE_FURNITURE, collision_type,
133 pre_solve=self._furniture_collision_pre_solve_handler)
[333]134 self.space.add_collision_handler(
135 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
136 pre_solve=self._claw_attack_collision_pre_solve_handler)
[188]137
[37]138 def add_walls(self):
[21]139 self.walls = []
140 body = pymunk.Body()
[84]141 body.position = (0, 0)
[53]142 walls = self._level.get_walls()
143 for wall in walls:
[279]144 if len(wall) < 2:
145 # Don't try to add a useless wall
146 continue
[53]147 corners = wall
148 corner = corners[-1]
149 for next_corner in corners:
150 wall = pymunk.Segment(body, corner, next_corner, 5)
[301]151 wall.collision_type = COLLISION_TYPE_WALL
[53]152 wall.elasticity = 1.0
153 self.walls.append(wall)
154 corner = next_corner
[21]155 self.space.add(*self.walls)
156
[145]157 def add_game_objects(self):
[191]158 for drawable in self._level.drawables:
[145]159 self._drawables.add(drawable)
160
[37]161 def add_protagonist(self):
[276]162 self.protagonist = self.world.protagonist
163 self.protagonist.change_space(self.space)
[505]164 self.world.rooms += 1
[107]165 self._drawables.add(self.protagonist)
[21]166
[505]167 def save_progress(self):
168 if self.name == Level.game_starting_point()[0]:
169 return
170 self.world.level = (self.name, (self.protagonist.physicser.position.x,
171 self.protagonist.physicser.position.y))
172 self.world.save()
173
[18]174 def handle_event(self, ev):
[20]175 if ev.type == pygame.locals.KEYDOWN:
176 if ev.key == pygame.locals.K_ESCAPE:
[480]177 if options.debug:
178 print ('Died at: (%i,%i)'
179 % (self.protagonist.physicser.position.x,
180 self.protagonist.physicser.position.y))
[437]181 if self._level.is_starting_level():
182 QuitEvent.post()
183 return
[440]184 self.protagonist.die()
[437]185 return
[336]186 cmd_key = self.keys.get_command_key(ev.key)
187 if cmd_key is not None:
188 self.protagonist.handle_keypress(cmd_key)
[180]189 elif DoorEvent.matches(ev):
190 self.protagonist.set_position(ev.dest_pos)
[471]191 if ev.destination is not None and ev.destination != self.name:
[512]192 if options.debug:
193 print 'Teleporting to %s' % ev.destination
[180]194 # Go to anther screen
[190]195 self._disable_render = True
[276]196 ScreenChange.post(ev.destination)
[190]197 return
[180]198 # else we're teleporting within the screen, and just the
199 # position change is enough
[440]200 elif DeathEvent.matches(ev):
201 self._disable_render = True
202 self.world.load()
203 self.world.deaths += 1
204 level, pos = Level.game_starting_point()
205 self.protagonist.set_position(pos)
206 ScreenChange.post(level)
[520]207 elif AddDrawableEvent.matches(ev):
208 self._drawables.add(ev.drawable)
209 if ev.drawable.overlay:
210 self._level.overlay_drawables.append(ev.drawable.overlay)
[34]211 self.keys.handle_event(ev)
[18]212
[87]213 def _calc_viewport(self, level_surface, display_surface):
214 level_size = level_surface.get_size()
215 display_size = display_surface.get_size()
[93]216 protagnist_pos = self.protagonist.physicser.get_render_position(
[127]217 level_surface)
[87]218 x_wide = display_size[0] // 2
219 y_wide = display_size[1] // 2
[127]220 if display_size[0] > level_size[0]:
221 x = -(display_size[0] - level_size[0]) // 2
222 elif protagnist_pos[0] < x_wide:
[87]223 x = 0
224 elif protagnist_pos[0] > level_size[0] - x_wide:
225 x = level_size[0] - display_size[0]
226 else:
227 x = protagnist_pos[0] - x_wide
[127]228 if display_size[1] > level_size[1]:
229 y = -(display_size[1] - level_size[1]) // 2
230 elif protagnist_pos[1] < y_wide:
[87]231 y = 0
232 elif protagnist_pos[1] > level_size[1] - y_wide:
233 y = level_size[1] - display_size[1]
234 else:
235 y = protagnist_pos[1] - y_wide
236 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
237
[18]238 def render(self, surface):
[190]239 if self._disable_render:
240 return
[511]241 if self._background is None:
242 bg = self._level.get_background()
243 self._background = pygame.surface.Surface(bg.get_size())
244 self._background.blit(bg, (0, 0))
245 self._surface = pygame.surface.Surface(self._background.get_size())
246 render_rect = self._calc_viewport(self._surface, surface)
247 self._surface.set_clip(render_rect)
248 self._surface.blit(self._background, render_rect.topleft, render_rect)
[105]249 for drawable in self._drawables:
[511]250 drawable.render(self._surface)
251 surface.blit(self._surface, (0, 0), render_rect)
[396]252 # Maximum width we allow for overlays
[511]253 max_width = min(render_rect.width, self._surface.get_width())
[520]254 for overlay in reversed(self._level.overlay_drawables):
[191]255 if overlay.is_visible():
[396]256 overlay.render(surface, render_rect.topleft, max_width)
[520]257 break
[243]258 self.render_health_bar(surface)
[34]259
260 def tick_protagonist(self):
[100]261 dx, dy = self.keys.get_direction()
[47]262 self.protagonist.set_direction(dx, dy)
[371]263 if self.keys.is_attacking():
[393]264 self._handle_result(self.protagonist.handle_attack_key_down())
[34]265
266 def tick(self, seconds):
[303]267 super(AreaScreen, self).tick(seconds)
[34]268 self.tick_protagonist()
[143]269 for drawable in self._drawables:
[393]270 self._handle_result(drawable.update(seconds))
271
272 def _handle_result(self, result):
273 if result is not None:
274 for drawable in result.add:
275 self._drawables.add(drawable)
[520]276 if drawable.overlay:
277 self._level.overlay_drawables.add(drawable.overlay)
[393]278 for drawable in result.remove:
279 self._drawables.remove(drawable)
[520]280 if drawable.overlay:
281 self._level.overlay_drawables.remove(drawable.overlay)
[243]282
[258]283 def render_health_bar(self, surface, damage_experienced=None):
[347]284 bar_surface = pygame.Surface((110, 50)).convert(surface)
[258]285 if damage_experienced:
286 health_box_colour = pygame.color.THECOLORS['red']
287 else:
288 health_box_colour = pygame.color.THECOLORS['white']
[347]289 bar_surface.fill(health_box_colour)
[246]290 if self.protagonist.in_human_form():
[243]291 health_colour = pygame.color.THECOLORS['red']
292 else:
[340]293 health_colour = pygame.color.THECOLORS['violetred3']
[347]294 rect = pygame.Rect(5, 5, self.protagonist.get_health_level(), 40)
295 pygame.draw.rect(bar_surface, health_colour, rect, 0)
296 bar_surface.set_alpha(192)
[365]297 y_pos = surface.get_height() - 20 - bar_surface.get_height()
298 surface.blit(bar_surface, (20, y_pos))
Note: See TracBrowser for help on using the repository browser.