source: nagslang/screens/area.py

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

Some flake8 fixes

File size: 12.8 KB
RevLine 
[18]1"""Display a game area."""
2
[689]3from __future__ import print_function
4
[20]5import pygame
[21]6import pymunk
7import pymunk.pygame_util
[20]8
[555]9from nagslang.resources import resources
10from nagslang.mutators import ImageCentre, scaler
[480]11from nagslang.options import options
[301]12from nagslang.constants import (
[319]13 COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS,
[336]14 COLLISION_TYPE_FURNITURE, COLLISION_TYPE_WEREWOLF_ATTACK,
[634]15 CMD_TOGGLE_FORM, CMD_ACTION, PROTAGONIST_HEALTH_MAX_LEVEL)
[520]16from nagslang.events import (
17 AddDrawableEvent, DeathEvent, DoorEvent, QuitEvent, ScreenChange)
[647]18from nagslang.game_object import SplashImage
[50]19from nagslang.level import Level
[65]20from nagslang.screens.base import Screen
[269]21from nagslang.sound import sound
[18]22
[83]23
[34]24class ControlKeys(object):
[100]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
[371]32 attack_keys = set([pygame.locals.K_z, pygame.locals.K_LCTRL])
33
[336]34 command_keys = {
35 pygame.locals.K_c: CMD_TOGGLE_FORM,
36 pygame.locals.K_SPACE: CMD_ACTION,
37 }
38
[34]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
[100]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
[371]62 def is_attacking(self):
63 return bool(self.keys_down & self.attack_keys)
64
[336]65 def get_command_key(self, key):
66 return self.command_keys.get(key, None)
67
[34]68
[107]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
[18]87class AreaScreen(Screen):
[21]88
[37]89 def setup(self):
[190]90 self._disable_render = False # Avoid redrawing on scene changes
[34]91 self.keys = ControlKeys()
[277]92 self._level = Level(self.name, self.world)
[145]93 self._level.load(self.space)
[107]94 self._drawables = Drawables()
[37]95 self.add_walls()
[188]96 self._add_collision_handlers()
[276]97 self.add_protagonist()
[145]98 self.add_game_objects()
[505]99 self.save_progress()
[608]100 sound.play_music(self._level.music, self._level.music_volume)
[511]101 self._background = None
102 self._surface = None
[21]103
[272]104 def teardown(self):
105 sound.stop()
[656]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)
[272]113
[321]114 @classmethod
115 def list_areas(self):
116 return Level.list_levels()
117
[319]118 def _player_collision_pre_solve_handler(self, space, arbiter):
[188]119 gobj = arbiter.shapes[1].physicser.game_object
[256]120 result = gobj.collide_with_protagonist(self.protagonist)
[192]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`.
[333]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
[188]131
[319]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
[188]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,
[319]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)
[333]146 self.space.add_collision_handler(
147 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
148 pre_solve=self._claw_attack_collision_pre_solve_handler)
[188]149
[37]150 def add_walls(self):
[21]151 self.walls = []
152 body = pymunk.Body()
[84]153 body.position = (0, 0)
[53]154 walls = self._level.get_walls()
155 for wall in walls:
[279]156 if len(wall) < 2:
157 # Don't try to add a useless wall
158 continue
[53]159 corners = wall
160 corner = corners[-1]
161 for next_corner in corners:
162 wall = pymunk.Segment(body, corner, next_corner, 5)
[301]163 wall.collision_type = COLLISION_TYPE_WALL
[53]164 wall.elasticity = 1.0
165 self.walls.append(wall)
166 corner = next_corner
[21]167 self.space.add(*self.walls)
168
[145]169 def add_game_objects(self):
[191]170 for drawable in self._level.drawables:
[145]171 self._drawables.add(drawable)
172
[37]173 def add_protagonist(self):
[276]174 self.protagonist = self.world.protagonist
[626]175 self.protagonist.reset()
[276]176 self.protagonist.change_space(self.space)
[505]177 self.world.rooms += 1
[107]178 self._drawables.add(self.protagonist)
[21]179
[505]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
[18]187 def handle_event(self, ev):
[20]188 if ev.type == pygame.locals.KEYDOWN:
189 if ev.key == pygame.locals.K_ESCAPE:
[480]190 if options.debug:
[689]191 print('Died at: (%i,%i)'
192 % (self.protagonist.physicser.position.x,
193 self.protagonist.physicser.position.y))
[437]194 if self._level.is_starting_level():
195 QuitEvent.post()
196 return
[440]197 self.protagonist.die()
[437]198 return
[336]199 cmd_key = self.keys.get_command_key(ev.key)
200 if cmd_key is not None:
201 self.protagonist.handle_keypress(cmd_key)
[180]202 elif DoorEvent.matches(ev):
203 self.protagonist.set_position(ev.dest_pos)
[471]204 if ev.destination is not None and ev.destination != self.name:
[512]205 if options.debug:
[689]206 print('Teleporting to %s' % ev.destination)
[180]207 # Go to anther screen
[190]208 self._disable_render = True
[276]209 ScreenChange.post(ev.destination)
[190]210 return
[180]211 # else we're teleporting within the screen, and just the
212 # position change is enough
[440]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)
[520]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)
[34]224 self.keys.handle_event(ev)
[18]225
[87]226 def _calc_viewport(self, level_surface, display_surface):
227 level_size = level_surface.get_size()
228 display_size = display_surface.get_size()
[93]229 protagnist_pos = self.protagonist.physicser.get_render_position(
[127]230 level_surface)
[87]231 x_wide = display_size[0] // 2
232 y_wide = display_size[1] // 2
[127]233 if display_size[0] > level_size[0]:
234 x = -(display_size[0] - level_size[0]) // 2
235 elif protagnist_pos[0] < x_wide:
[87]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
[127]241 if display_size[1] > level_size[1]:
242 y = -(display_size[1] - level_size[1]) // 2
243 elif protagnist_pos[1] < y_wide:
[87]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
[18]251 def render(self, surface):
[190]252 if self._disable_render:
253 return
[511]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)
[105]262 for drawable in self._drawables:
[511]263 drawable.render(self._surface)
264 surface.blit(self._surface, (0, 0), render_rect)
[396]265 # Maximum width we allow for overlays
[511]266 max_width = min(render_rect.width, self._surface.get_width())
[520]267 for overlay in reversed(self._level.overlay_drawables):
[191]268 if overlay.is_visible():
[396]269 overlay.render(surface, render_rect.topleft, max_width)
[520]270 break
[243]271 self.render_health_bar(surface)
[555]272 self.render_inventory(surface)
[34]273
274 def tick_protagonist(self):
[100]275 dx, dy = self.keys.get_direction()
[47]276 self.protagonist.set_direction(dx, dy)
[371]277 if self.keys.is_attacking():
[393]278 self._handle_result(self.protagonist.handle_attack_key_down())
[34]279
280 def tick(self, seconds):
[303]281 super(AreaScreen, self).tick(seconds)
[34]282 self.tick_protagonist()
[143]283 for drawable in self._drawables:
[393]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)
[520]290 if drawable.overlay:
291 self._level.overlay_drawables.add(drawable.overlay)
[393]292 for drawable in result.remove:
293 self._drawables.remove(drawable)
[520]294 if drawable.overlay:
295 self._level.overlay_drawables.remove(drawable.overlay)
[243]296
[258]297 def render_health_bar(self, surface, damage_experienced=None):
[555]298 bar_surface = pygame.Surface((110, 40)).convert(surface)
[258]299 if damage_experienced:
300 health_box_colour = pygame.color.THECOLORS['red']
301 else:
302 health_box_colour = pygame.color.THECOLORS['white']
[347]303 bar_surface.fill(health_box_colour)
[246]304 if self.protagonist.in_human_form():
[243]305 health_colour = pygame.color.THECOLORS['red']
306 else:
[340]307 health_colour = pygame.color.THECOLORS['violetred3']
[634]308 health = self.protagonist.get_health_level()
309 rect = pygame.Rect(
310 5, 5, (100 * health) / PROTAGONIST_HEALTH_MAX_LEVEL, 30)
[347]311 pygame.draw.rect(bar_surface, health_colour, rect, 0)
312 bar_surface.set_alpha(192)
[365]313 y_pos = surface.get_height() - 20 - bar_surface.get_height()
314 surface.blit(bar_surface, (20, y_pos))
[555]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))
[647]338
339 def splash(self):
[650]340 AddDrawableEvent.post(SplashImage(resources.get_image('title.png'), 5))
Note: See TracBrowser for help on using the repository browser.