source: nagslang/screens/area.py@ 437:d087dfb10896

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

Replace menu and death screen with the starting level

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