source: nagslang/screens/area.py@ 371:21c1c329f8e3

Last change on this file since 371:21c1c329f8e3 was 371:21c1c329f8e3, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Automatic weapons.

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