source: nagslang/screens/area.py@ 308:3dee86b6c216

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

Enemies leave corpses

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