source: nagslang/screens/area.py@ 321:0d7885e2f063

Last change on this file since 321:0d7885e2f063 was 321:0d7885e2f063, checked in by Simon Cross <hodgestar@…>, 8 years ago

Add means for listing levels and areas.

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