source: nagslang/screens/area.py@ 520:3f79a77ef1e3

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

Ephemeral messages

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