source: nagslang/screens/area.py@ 634:45eff33c3dad

Last change on this file since 634:45eff33c3dad was 634:45eff33c3dad, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Increased health.

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