source: nagslang/screens/area.py@ 655:baacd0462d8e

Last change on this file since 655:baacd0462d8e was 650:92c3e02792dc, checked in by Stefano Rivera <stefano@…>, 8 years ago

Splash is too long

File size: 12.4 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
105 @classmethod
106 def list_areas(self):
107 return Level.list_levels()
108
109 def _player_collision_pre_solve_handler(self, space, arbiter):
110 gobj = arbiter.shapes[1].physicser.game_object
111 result = gobj.collide_with_protagonist(self.protagonist)
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`.
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
122
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
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,
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)
137 self.space.add_collision_handler(
138 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
139 pre_solve=self._claw_attack_collision_pre_solve_handler)
140
141 def add_walls(self):
142 self.walls = []
143 body = pymunk.Body()
144 body.position = (0, 0)
145 walls = self._level.get_walls()
146 for wall in walls:
147 if len(wall) < 2:
148 # Don't try to add a useless wall
149 continue
150 corners = wall
151 corner = corners[-1]
152 for next_corner in corners:
153 wall = pymunk.Segment(body, corner, next_corner, 5)
154 wall.collision_type = COLLISION_TYPE_WALL
155 wall.elasticity = 1.0
156 self.walls.append(wall)
157 corner = next_corner
158 self.space.add(*self.walls)
159
160 def add_game_objects(self):
161 for drawable in self._level.drawables:
162 self._drawables.add(drawable)
163
164 def add_protagonist(self):
165 self.protagonist = self.world.protagonist
166 self.protagonist.reset()
167 self.protagonist.change_space(self.space)
168 self.world.rooms += 1
169 self._drawables.add(self.protagonist)
170
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
178 def handle_event(self, ev):
179 if ev.type == pygame.locals.KEYDOWN:
180 if ev.key == pygame.locals.K_ESCAPE:
181 if options.debug:
182 print ('Died at: (%i,%i)'
183 % (self.protagonist.physicser.position.x,
184 self.protagonist.physicser.position.y))
185 if self._level.is_starting_level():
186 QuitEvent.post()
187 return
188 self.protagonist.die()
189 return
190 cmd_key = self.keys.get_command_key(ev.key)
191 if cmd_key is not None:
192 self.protagonist.handle_keypress(cmd_key)
193 elif DoorEvent.matches(ev):
194 self.protagonist.set_position(ev.dest_pos)
195 if ev.destination is not None and ev.destination != self.name:
196 if options.debug:
197 print 'Teleporting to %s' % ev.destination
198 # Go to anther screen
199 self._disable_render = True
200 ScreenChange.post(ev.destination)
201 return
202 # else we're teleporting within the screen, and just the
203 # position change is enough
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)
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)
215 self.keys.handle_event(ev)
216
217 def _calc_viewport(self, level_surface, display_surface):
218 level_size = level_surface.get_size()
219 display_size = display_surface.get_size()
220 protagnist_pos = self.protagonist.physicser.get_render_position(
221 level_surface)
222 x_wide = display_size[0] // 2
223 y_wide = display_size[1] // 2
224 if display_size[0] > level_size[0]:
225 x = -(display_size[0] - level_size[0]) // 2
226 elif protagnist_pos[0] < x_wide:
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
232 if display_size[1] > level_size[1]:
233 y = -(display_size[1] - level_size[1]) // 2
234 elif protagnist_pos[1] < y_wide:
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
242 def render(self, surface):
243 if self._disable_render:
244 return
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)
253 for drawable in self._drawables:
254 drawable.render(self._surface)
255 surface.blit(self._surface, (0, 0), render_rect)
256 # Maximum width we allow for overlays
257 max_width = min(render_rect.width, self._surface.get_width())
258 for overlay in reversed(self._level.overlay_drawables):
259 if overlay.is_visible():
260 overlay.render(surface, render_rect.topleft, max_width)
261 break
262 self.render_health_bar(surface)
263 self.render_inventory(surface)
264
265 def tick_protagonist(self):
266 dx, dy = self.keys.get_direction()
267 self.protagonist.set_direction(dx, dy)
268 if self.keys.is_attacking():
269 self._handle_result(self.protagonist.handle_attack_key_down())
270
271 def tick(self, seconds):
272 super(AreaScreen, self).tick(seconds)
273 self.tick_protagonist()
274 for drawable in self._drawables:
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)
281 if drawable.overlay:
282 self._level.overlay_drawables.add(drawable.overlay)
283 for drawable in result.remove:
284 self._drawables.remove(drawable)
285 if drawable.overlay:
286 self._level.overlay_drawables.remove(drawable.overlay)
287
288 def render_health_bar(self, surface, damage_experienced=None):
289 bar_surface = pygame.Surface((110, 40)).convert(surface)
290 if damage_experienced:
291 health_box_colour = pygame.color.THECOLORS['red']
292 else:
293 health_box_colour = pygame.color.THECOLORS['white']
294 bar_surface.fill(health_box_colour)
295 if self.protagonist.in_human_form():
296 health_colour = pygame.color.THECOLORS['red']
297 else:
298 health_colour = pygame.color.THECOLORS['violetred3']
299 health = self.protagonist.get_health_level()
300 rect = pygame.Rect(
301 5, 5, (100 * health) / PROTAGONIST_HEALTH_MAX_LEVEL, 30)
302 pygame.draw.rect(bar_surface, health_colour, rect, 0)
303 bar_surface.set_alpha(192)
304 y_pos = surface.get_height() - 20 - bar_surface.get_height()
305 surface.blit(bar_surface, (20, y_pos))
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))
329
330 def splash(self):
331 AddDrawableEvent.post(SplashImage(resources.get_image('title.png'), 5))
Note: See TracBrowser for help on using the repository browser.