source: nagslang/screens/area.py@ 512:a46767c61ad6

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

debug print on teleport

File size: 10.6 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 ScreenChange, DoorEvent, QuitEvent, DeathEvent
13from nagslang.level import Level
14from nagslang.screens.base import Screen
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 self.save_progress()
94 sound.play_music("POL-cyber-factory-short.ogg")
95 self._background = None
96 self._surface = None
97
98 def teardown(self):
99 sound.stop()
100
101 @classmethod
102 def list_areas(self):
103 return Level.list_levels()
104
105 def _player_collision_pre_solve_handler(self, space, arbiter):
106 gobj = arbiter.shapes[1].physicser.game_object
107 result = gobj.collide_with_protagonist(self.protagonist)
108 # The collision handler must return `True` or `False`. We don't want to
109 # accidentally reject collisions from handlers that return `None`, so
110 # we explicitly check for `False` and treate everything else as `True`.
111 return result is not False
112
113 def _claw_attack_collision_pre_solve_handler(self, space, arbiter):
114 claw = arbiter.shapes[0].physicser.game_object
115 gobj = arbiter.shapes[1].physicser.game_object
116 result = gobj.collide_with_claw_attack(claw)
117 return result is not False
118
119 def _furniture_collision_pre_solve_handler(self, space, arbiter):
120 furniture = arbiter.shapes[0].physicser.game_object
121 gobj = arbiter.shapes[1].physicser.game_object
122 result = gobj.collide_with_furniture(furniture)
123 return result is not False
124
125 def _add_collision_handlers(self):
126 for collision_type in CALLBACK_COLLIDERS:
127 self.space.add_collision_handler(
128 COLLISION_TYPE_PLAYER, collision_type,
129 pre_solve=self._player_collision_pre_solve_handler)
130 self.space.add_collision_handler(
131 COLLISION_TYPE_FURNITURE, collision_type,
132 pre_solve=self._furniture_collision_pre_solve_handler)
133 self.space.add_collision_handler(
134 COLLISION_TYPE_WEREWOLF_ATTACK, collision_type,
135 pre_solve=self._claw_attack_collision_pre_solve_handler)
136
137 def add_walls(self):
138 self.walls = []
139 body = pymunk.Body()
140 body.position = (0, 0)
141 walls = self._level.get_walls()
142 for wall in walls:
143 if len(wall) < 2:
144 # Don't try to add a useless wall
145 continue
146 corners = wall
147 corner = corners[-1]
148 for next_corner in corners:
149 wall = pymunk.Segment(body, corner, next_corner, 5)
150 wall.collision_type = COLLISION_TYPE_WALL
151 wall.elasticity = 1.0
152 self.walls.append(wall)
153 corner = next_corner
154 self.space.add(*self.walls)
155
156 def add_game_objects(self):
157 for drawable in self._level.drawables:
158 self._drawables.add(drawable)
159
160 def add_protagonist(self):
161 self.protagonist = self.world.protagonist
162 self.protagonist.change_space(self.space)
163 self.world.rooms += 1
164 self._drawables.add(self.protagonist)
165
166 def save_progress(self):
167 if self.name == Level.game_starting_point()[0]:
168 return
169 self.world.level = (self.name, (self.protagonist.physicser.position.x,
170 self.protagonist.physicser.position.y))
171 self.world.save()
172
173 def handle_event(self, ev):
174 if ev.type == pygame.locals.KEYDOWN:
175 if ev.key == pygame.locals.K_ESCAPE:
176 if options.debug:
177 print ('Died at: (%i,%i)'
178 % (self.protagonist.physicser.position.x,
179 self.protagonist.physicser.position.y))
180 if self._level.is_starting_level():
181 QuitEvent.post()
182 return
183 self.protagonist.die()
184 return
185 cmd_key = self.keys.get_command_key(ev.key)
186 if cmd_key is not None:
187 self.protagonist.handle_keypress(cmd_key)
188 elif DoorEvent.matches(ev):
189 self.protagonist.set_position(ev.dest_pos)
190 if ev.destination is not None and ev.destination != self.name:
191 if options.debug:
192 print 'Teleporting to %s' % ev.destination
193 # Go to anther screen
194 self._disable_render = True
195 ScreenChange.post(ev.destination)
196 return
197 # else we're teleporting within the screen, and just the
198 # position change is enough
199 elif DeathEvent.matches(ev):
200 self._disable_render = True
201 self.world.load()
202 self.world.deaths += 1
203 level, pos = Level.game_starting_point()
204 self.protagonist.set_position(pos)
205 ScreenChange.post(level)
206
207 self.keys.handle_event(ev)
208
209 def _calc_viewport(self, level_surface, display_surface):
210 level_size = level_surface.get_size()
211 display_size = display_surface.get_size()
212 protagnist_pos = self.protagonist.physicser.get_render_position(
213 level_surface)
214 x_wide = display_size[0] // 2
215 y_wide = display_size[1] // 2
216 if display_size[0] > level_size[0]:
217 x = -(display_size[0] - level_size[0]) // 2
218 elif protagnist_pos[0] < x_wide:
219 x = 0
220 elif protagnist_pos[0] > level_size[0] - x_wide:
221 x = level_size[0] - display_size[0]
222 else:
223 x = protagnist_pos[0] - x_wide
224 if display_size[1] > level_size[1]:
225 y = -(display_size[1] - level_size[1]) // 2
226 elif protagnist_pos[1] < y_wide:
227 y = 0
228 elif protagnist_pos[1] > level_size[1] - y_wide:
229 y = level_size[1] - display_size[1]
230 else:
231 y = protagnist_pos[1] - y_wide
232 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
233
234 def render(self, surface):
235 if self._disable_render:
236 return
237 if self._background is None:
238 bg = self._level.get_background()
239 self._background = pygame.surface.Surface(bg.get_size())
240 self._background.blit(bg, (0, 0))
241 self._surface = pygame.surface.Surface(self._background.get_size())
242 render_rect = self._calc_viewport(self._surface, surface)
243 self._surface.set_clip(render_rect)
244 self._surface.blit(self._background, render_rect.topleft, render_rect)
245 for drawable in self._drawables:
246 drawable.render(self._surface)
247 surface.blit(self._surface, (0, 0), render_rect)
248 # Maximum width we allow for overlays
249 max_width = min(render_rect.width, self._surface.get_width())
250 for overlay in self._level.overlay_drawables:
251 if overlay.is_visible():
252 overlay.render(surface, render_rect.topleft, max_width)
253 self.render_health_bar(surface)
254
255 def tick_protagonist(self):
256 dx, dy = self.keys.get_direction()
257 self.protagonist.set_direction(dx, dy)
258 if self.keys.is_attacking():
259 self._handle_result(self.protagonist.handle_attack_key_down())
260
261 def tick(self, seconds):
262 super(AreaScreen, self).tick(seconds)
263 self.tick_protagonist()
264 for drawable in self._drawables:
265 self._handle_result(drawable.update(seconds))
266
267 def _handle_result(self, result):
268 if result is not None:
269 for drawable in result.add:
270 self._drawables.add(drawable)
271 for drawable in result.remove:
272 self._drawables.remove(drawable)
273
274 def render_health_bar(self, surface, damage_experienced=None):
275 bar_surface = pygame.Surface((110, 50)).convert(surface)
276 if damage_experienced:
277 health_box_colour = pygame.color.THECOLORS['red']
278 else:
279 health_box_colour = pygame.color.THECOLORS['white']
280 bar_surface.fill(health_box_colour)
281 if self.protagonist.in_human_form():
282 health_colour = pygame.color.THECOLORS['red']
283 else:
284 health_colour = pygame.color.THECOLORS['violetred3']
285 rect = pygame.Rect(5, 5, self.protagonist.get_health_level(), 40)
286 pygame.draw.rect(bar_surface, health_colour, rect, 0)
287 bar_surface.set_alpha(192)
288 y_pos = surface.get_height() - 20 - bar_surface.get_height()
289 surface.blit(bar_surface, (20, y_pos))
Note: See TracBrowser for help on using the repository browser.