source: nagslang/screens/area.py@ 647:aeb366d97774

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

Show splash image on startup

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