source: nagslang/screens/area.py@ 689:45d2a6aef3a4

Last change on this file since 689:45d2a6aef3a4 was 689:45d2a6aef3a4, checked in by Neil Muller <drnlmuller@…>, 2 years ago

Some flake8 fixes

File size: 12.8 KB
Line 
1"""Display a game area."""
2
3from __future__ import print_function
4
5import pygame
6import pymunk
7import pymunk.pygame_util
8
9from nagslang.resources import resources
10from nagslang.mutators import ImageCentre, scaler
11from nagslang.options import options
12from nagslang.constants import (
13 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS,
14 COLLISION_TYPE_FURNITURE, COLLISION_TYPE_WEREWOLF_ATTACK,
15 CMD_TOGGLE_FORM, CMD_ACTION, PROTAGONIST_HEALTH_MAX_LEVEL)
16from nagslang.events import (
17 AddDrawableEvent, DeathEvent, DoorEvent, QuitEvent, ScreenChange)
18from nagslang.game_object import SplashImage
19from nagslang.level import Level
20from nagslang.screens.base import Screen
21from nagslang.sound import sound
22
23
24class ControlKeys(object):
25 direction_keys = {
26 (0, 1): set([pygame.locals.K_UP, pygame.locals.K_w]),
27 (0, -1): set([pygame.locals.K_DOWN, pygame.locals.K_s]),
28 (-1, 0): set([pygame.locals.K_LEFT, pygame.locals.K_a]),
29 (1, 0): set([pygame.locals.K_RIGHT, pygame.locals.K_d]),
30 }
31
32 attack_keys = set([pygame.locals.K_z, pygame.locals.K_LCTRL])
33
34 command_keys = {
35 pygame.locals.K_c: CMD_TOGGLE_FORM,
36 pygame.locals.K_SPACE: CMD_ACTION,
37 }
38
39 def __init__(self):
40 self.keys_down = set()
41
42 def key_down(self, key):
43 self.keys_down.add(key)
44
45 def key_up(self, key):
46 self.keys_down.discard(key)
47
48 def handle_event(self, ev):
49 if ev.type == pygame.locals.KEYDOWN:
50 self.key_down(ev.key)
51 elif ev.type == pygame.locals.KEYUP:
52 self.key_up(ev.key)
53
54 def get_direction(self):
55 dx, dy = 0, 0
56 for (tx, ty), keys in self.direction_keys.iteritems():
57 if self.keys_down & keys:
58 dx += tx
59 dy += ty
60 return (dx, dy)
61
62 def is_attacking(self):
63 return bool(self.keys_down & self.attack_keys)
64
65 def get_command_key(self, key):
66 return self.command_keys.get(key, None)
67
68
69class Drawables(object):
70 def __init__(self):
71 self._drawables = {}
72
73 def add(self, drawable):
74 self._drawables.setdefault(drawable.zorder, []).append(drawable)
75
76 def remove(self, drawable):
77 self._drawables[drawable.zorder].remove(drawable)
78
79 def get_drawables(self):
80 for zorder in sorted(self._drawables):
81 for drawable in self._drawables[zorder]:
82 yield drawable
83
84 __iter__ = get_drawables
85
86
87class AreaScreen(Screen):
88
89 def setup(self):
90 self._disable_render = False # Avoid redrawing on scene changes
91 self.keys = ControlKeys()
92 self._level = Level(self.name, self.world)
93 self._level.load(self.space)
94 self._drawables = Drawables()
95 self.add_walls()
96 self._add_collision_handlers()
97 self.add_protagonist()
98 self.add_game_objects()
99 self.save_progress()
100 sound.play_music(self._level.music, self._level.music_volume)
101 self._background = None
102 self._surface = None
103
104 def teardown(self):
105 sound.stop()
106 for collision_type in CALLBACK_COLLIDERS:
107 self.space.remove_collision_handler(
108 COLLISION_TYPE_PLAYER, collision_type)
109 self.space.remove_collision_handler(
110 COLLISION_TYPE_FURNITURE, collision_type)
111 self.space.remove_collision_handler(
112 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type)
113
114 @classmethod
115 def list_areas(self):
116 return Level.list_levels()
117
118 def _player_collision_pre_solve_handler(self, space, arbiter):
119 gobj = arbiter.shapes[1].physicser.game_object
120 result = gobj.collide_with_protagonist(self.protagonist)
121 # The collision handler must return `True` or `False`. We don't want to
122 # accidentally reject collisions from handlers that return `None`, so
123 # we explicitly check for `False` and treate everything else as `True`.
124 return result is not False
125
126 def _claw_attack_collision_pre_solve_handler(self, space, arbiter):
127 claw = arbiter.shapes[0].physicser.game_object
128 gobj = arbiter.shapes[1].physicser.game_object
129 result = gobj.collide_with_claw_attack(claw)
130 return result is not False
131
132 def _furniture_collision_pre_solve_handler(self, space, arbiter):
133 furniture = arbiter.shapes[0].physicser.game_object
134 gobj = arbiter.shapes[1].physicser.game_object
135 result = gobj.collide_with_furniture(furniture)
136 return result is not False
137
138 def _add_collision_handlers(self):
139 for collision_type in CALLBACK_COLLIDERS:
140 self.space.add_collision_handler(
141 COLLISION_TYPE_PLAYER, collision_type,
142 pre_solve=self._player_collision_pre_solve_handler)
143 self.space.add_collision_handler(
144 COLLISION_TYPE_FURNITURE, collision_type,
145 pre_solve=self._furniture_collision_pre_solve_handler)
146 self.space.add_collision_handler(
147 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
148 pre_solve=self._claw_attack_collision_pre_solve_handler)
149
150 def add_walls(self):
151 self.walls = []
152 body = pymunk.Body()
153 body.position = (0, 0)
154 walls = self._level.get_walls()
155 for wall in walls:
156 if len(wall) < 2:
157 # Don't try to add a useless wall
158 continue
159 corners = wall
160 corner = corners[-1]
161 for next_corner in corners:
162 wall = pymunk.Segment(body, corner, next_corner, 5)
163 wall.collision_type = COLLISION_TYPE_WALL
164 wall.elasticity = 1.0
165 self.walls.append(wall)
166 corner = next_corner
167 self.space.add(*self.walls)
168
169 def add_game_objects(self):
170 for drawable in self._level.drawables:
171 self._drawables.add(drawable)
172
173 def add_protagonist(self):
174 self.protagonist = self.world.protagonist
175 self.protagonist.reset()
176 self.protagonist.change_space(self.space)
177 self.world.rooms += 1
178 self._drawables.add(self.protagonist)
179
180 def save_progress(self):
181 if self.name == Level.game_starting_point()[0]:
182 return
183 self.world.level = (self.name, (self.protagonist.physicser.position.x,
184 self.protagonist.physicser.position.y))
185 self.world.save()
186
187 def handle_event(self, ev):
188 if ev.type == pygame.locals.KEYDOWN:
189 if ev.key == pygame.locals.K_ESCAPE:
190 if options.debug:
191 print('Died at: (%i,%i)'
192 % (self.protagonist.physicser.position.x,
193 self.protagonist.physicser.position.y))
194 if self._level.is_starting_level():
195 QuitEvent.post()
196 return
197 self.protagonist.die()
198 return
199 cmd_key = self.keys.get_command_key(ev.key)
200 if cmd_key is not None:
201 self.protagonist.handle_keypress(cmd_key)
202 elif DoorEvent.matches(ev):
203 self.protagonist.set_position(ev.dest_pos)
204 if ev.destination is not None and ev.destination != self.name:
205 if options.debug:
206 print('Teleporting to %s' % ev.destination)
207 # Go to anther screen
208 self._disable_render = True
209 ScreenChange.post(ev.destination)
210 return
211 # else we're teleporting within the screen, and just the
212 # position change is enough
213 elif DeathEvent.matches(ev):
214 self._disable_render = True
215 self.world.load()
216 self.world.deaths += 1
217 level, pos = Level.game_starting_point()
218 self.protagonist.set_position(pos)
219 ScreenChange.post(level)
220 elif AddDrawableEvent.matches(ev):
221 self._drawables.add(ev.drawable)
222 if ev.drawable.overlay:
223 self._level.overlay_drawables.append(ev.drawable.overlay)
224 self.keys.handle_event(ev)
225
226 def _calc_viewport(self, level_surface, display_surface):
227 level_size = level_surface.get_size()
228 display_size = display_surface.get_size()
229 protagnist_pos = self.protagonist.physicser.get_render_position(
230 level_surface)
231 x_wide = display_size[0] // 2
232 y_wide = display_size[1] // 2
233 if display_size[0] > level_size[0]:
234 x = -(display_size[0] - level_size[0]) // 2
235 elif protagnist_pos[0] < x_wide:
236 x = 0
237 elif protagnist_pos[0] > level_size[0] - x_wide:
238 x = level_size[0] - display_size[0]
239 else:
240 x = protagnist_pos[0] - x_wide
241 if display_size[1] > level_size[1]:
242 y = -(display_size[1] - level_size[1]) // 2
243 elif protagnist_pos[1] < y_wide:
244 y = 0
245 elif protagnist_pos[1] > level_size[1] - y_wide:
246 y = level_size[1] - display_size[1]
247 else:
248 y = protagnist_pos[1] - y_wide
249 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
250
251 def render(self, surface):
252 if self._disable_render:
253 return
254 if self._background is None:
255 bg = self._level.get_background()
256 self._background = pygame.surface.Surface(bg.get_size())
257 self._background.blit(bg, (0, 0))
258 self._surface = pygame.surface.Surface(self._background.get_size())
259 render_rect = self._calc_viewport(self._surface, surface)
260 self._surface.set_clip(render_rect)
261 self._surface.blit(self._background, render_rect.topleft, render_rect)
262 for drawable in self._drawables:
263 drawable.render(self._surface)
264 surface.blit(self._surface, (0, 0), render_rect)
265 # Maximum width we allow for overlays
266 max_width = min(render_rect.width, self._surface.get_width())
267 for overlay in reversed(self._level.overlay_drawables):
268 if overlay.is_visible():
269 overlay.render(surface, render_rect.topleft, max_width)
270 break
271 self.render_health_bar(surface)
272 self.render_inventory(surface)
273
274 def tick_protagonist(self):
275 dx, dy = self.keys.get_direction()
276 self.protagonist.set_direction(dx, dy)
277 if self.keys.is_attacking():
278 self._handle_result(self.protagonist.handle_attack_key_down())
279
280 def tick(self, seconds):
281 super(AreaScreen, self).tick(seconds)
282 self.tick_protagonist()
283 for drawable in self._drawables:
284 self._handle_result(drawable.update(seconds))
285
286 def _handle_result(self, result):
287 if result is not None:
288 for drawable in result.add:
289 self._drawables.add(drawable)
290 if drawable.overlay:
291 self._level.overlay_drawables.add(drawable.overlay)
292 for drawable in result.remove:
293 self._drawables.remove(drawable)
294 if drawable.overlay:
295 self._level.overlay_drawables.remove(drawable.overlay)
296
297 def render_health_bar(self, surface, damage_experienced=None):
298 bar_surface = pygame.Surface((110, 40)).convert(surface)
299 if damage_experienced:
300 health_box_colour = pygame.color.THECOLORS['red']
301 else:
302 health_box_colour = pygame.color.THECOLORS['white']
303 bar_surface.fill(health_box_colour)
304 if self.protagonist.in_human_form():
305 health_colour = pygame.color.THECOLORS['red']
306 else:
307 health_colour = pygame.color.THECOLORS['violetred3']
308 health = self.protagonist.get_health_level()
309 rect = pygame.Rect(
310 5, 5, (100 * health) / PROTAGONIST_HEALTH_MAX_LEVEL, 30)
311 pygame.draw.rect(bar_surface, health_colour, rect, 0)
312 bar_surface.set_alpha(192)
313 y_pos = surface.get_height() - 20 - bar_surface.get_height()
314 surface.blit(bar_surface, (20, y_pos))
315
316 def render_inventory(self, surface):
317 items = len(self.world.inventory)
318 if not items:
319 return
320 padding = 4
321 img_size = 64
322 size = 32
323 inv_surf = pygame.Surface(
324 (padding + (size + padding) * items,
325 (2 * padding + size)))
326 inv_surf = inv_surf.convert(surface)
327 inv_surf.set_alpha(192)
328 inv_surf.fill(pygame.color.THECOLORS['white'])
329 for index, item in enumerate(sorted(self.world.inventory)):
330 img = resources.get_image(
331 'objects', item + '.png',
332 transforms=(ImageCentre((img_size, img_size)),
333 scaler((size, size))))
334 inv_surf.blit(img, (padding + index * (size + padding), padding))
335 y_pos = surface.get_height() - 20 - inv_surf.get_height()
336 x_pos = 130 + padding
337 surface.blit(inv_surf, (x_pos, y_pos))
338
339 def splash(self):
340 AddDrawableEvent.post(SplashImage(resources.get_image('title.png'), 5))
Note: See TracBrowser for help on using the repository browser.