source: nagslang/screens/area.py@ 393:8d961e05b7b6

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

Use Result to handle firing

File size: 9.4 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, EnemyDeathEvent, ClawEvent
12from nagslang.level import Level
13from nagslang.screens.base import Screen
14from nagslang.game_object import ClawAttack
15from nagslang.sound import sound
16
17
18class ControlKeys(object):
19 direction_keys = {
20 (0, 1): set([pygame.locals.K_UP, pygame.locals.K_w]),
21 (0, -1): set([pygame.locals.K_DOWN, pygame.locals.K_s]),
22 (-1, 0): set([pygame.locals.K_LEFT, pygame.locals.K_a]),
23 (1, 0): set([pygame.locals.K_RIGHT, pygame.locals.K_d]),
24 }
25
26 attack_keys = set([pygame.locals.K_z, pygame.locals.K_LCTRL])
27
28 command_keys = {
29 pygame.locals.K_c: CMD_TOGGLE_FORM,
30 pygame.locals.K_SPACE: CMD_ACTION,
31 }
32
33 def __init__(self):
34 self.keys_down = set()
35
36 def key_down(self, key):
37 self.keys_down.add(key)
38
39 def key_up(self, key):
40 self.keys_down.discard(key)
41
42 def handle_event(self, ev):
43 if ev.type == pygame.locals.KEYDOWN:
44 self.key_down(ev.key)
45 elif ev.type == pygame.locals.KEYUP:
46 self.key_up(ev.key)
47
48 def get_direction(self):
49 dx, dy = 0, 0
50 for (tx, ty), keys in self.direction_keys.iteritems():
51 if self.keys_down & keys:
52 dx += tx
53 dy += ty
54 return (dx, dy)
55
56 def is_attacking(self):
57 return bool(self.keys_down & self.attack_keys)
58
59 def get_command_key(self, key):
60 return self.command_keys.get(key, None)
61
62
63class Drawables(object):
64 def __init__(self):
65 self._drawables = {}
66
67 def add(self, drawable):
68 self._drawables.setdefault(drawable.zorder, []).append(drawable)
69
70 def remove(self, drawable):
71 self._drawables[drawable.zorder].remove(drawable)
72
73 def get_drawables(self):
74 for zorder in sorted(self._drawables):
75 for drawable in self._drawables[zorder]:
76 yield drawable
77
78 __iter__ = get_drawables
79
80
81class AreaScreen(Screen):
82
83 def setup(self):
84 self._disable_render = False # Avoid redrawing on scene changes
85 self.keys = ControlKeys()
86 self._level = Level(self.name, self.world)
87 self._level.load(self.space)
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 ScreenChange.post('menu')
166 cmd_key = self.keys.get_command_key(ev.key)
167 if cmd_key is not None:
168 self.protagonist.handle_keypress(cmd_key)
169 elif DoorEvent.matches(ev):
170 self.protagonist.set_position(ev.dest_pos)
171 if ev.destination != self.name:
172 # Go to anther screen
173 self._disable_render = True
174 self.world.rooms += 1
175 self.world.level = (ev.destination, ev.dest_pos)
176 ScreenChange.post(ev.destination)
177 return
178 # else we're teleporting within the screen, and just the
179 # position change is enough
180 elif EnemyDeathEvent.matches(ev):
181 self.world.kills += 1
182 elif ClawEvent.matches(ev):
183 claw_attack = ClawAttack(self.space, ev.source, ev.vector,
184 ev.damage)
185 self._drawables.add(claw_attack)
186 self.keys.handle_event(ev)
187
188 def _calc_viewport(self, level_surface, display_surface):
189 level_size = level_surface.get_size()
190 display_size = display_surface.get_size()
191 protagnist_pos = self.protagonist.physicser.get_render_position(
192 level_surface)
193 x_wide = display_size[0] // 2
194 y_wide = display_size[1] // 2
195 if display_size[0] > level_size[0]:
196 x = -(display_size[0] - level_size[0]) // 2
197 elif protagnist_pos[0] < x_wide:
198 x = 0
199 elif protagnist_pos[0] > level_size[0] - x_wide:
200 x = level_size[0] - display_size[0]
201 else:
202 x = protagnist_pos[0] - x_wide
203 if display_size[1] > level_size[1]:
204 y = -(display_size[1] - level_size[1]) // 2
205 elif protagnist_pos[1] < y_wide:
206 y = 0
207 elif protagnist_pos[1] > level_size[1] - y_wide:
208 y = level_size[1] - display_size[1]
209 else:
210 y = protagnist_pos[1] - y_wide
211 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
212
213 def render(self, surface):
214 if self._disable_render:
215 return
216 background = self._level.get_background()
217 mysurface = background.copy()
218 for drawable in self._drawables:
219 drawable.render(mysurface)
220 render_rect = self._calc_viewport(mysurface, surface)
221 surface.blit(mysurface, (0, 0), render_rect)
222 for overlay in self._level.overlay_drawables:
223 if overlay.is_visible():
224 overlay.render(surface, render_rect.topleft)
225 self.render_health_bar(surface)
226
227 def tick_protagonist(self):
228 dx, dy = self.keys.get_direction()
229 self.protagonist.set_direction(dx, dy)
230 if self.keys.is_attacking():
231 self._handle_result(self.protagonist.handle_attack_key_down())
232
233 def tick(self, seconds):
234 super(AreaScreen, self).tick(seconds)
235 self.tick_protagonist()
236 for drawable in self._drawables:
237 self._handle_result(drawable.update(seconds))
238
239 def _handle_result(self, result):
240 if result is not None:
241 for drawable in result.add:
242 self._drawables.add(drawable)
243 for drawable in result.remove:
244 self._drawables.remove(drawable)
245
246 def render_health_bar(self, surface, damage_experienced=None):
247 bar_surface = pygame.Surface((110, 50)).convert(surface)
248 if damage_experienced:
249 health_box_colour = pygame.color.THECOLORS['red']
250 else:
251 health_box_colour = pygame.color.THECOLORS['white']
252 bar_surface.fill(health_box_colour)
253 if self.protagonist.in_human_form():
254 health_colour = pygame.color.THECOLORS['red']
255 else:
256 health_colour = pygame.color.THECOLORS['violetred3']
257 rect = pygame.Rect(5, 5, self.protagonist.get_health_level(), 40)
258 pygame.draw.rect(bar_surface, health_colour, rect, 0)
259 bar_surface.set_alpha(192)
260 y_pos = surface.get_height() - 20 - bar_surface.get_height()
261 surface.blit(bar_surface, (20, y_pos))
Note: See TracBrowser for help on using the repository browser.