source: nagslang/screens/area.py@ 313:768e1d06155f

Last change on this file since 313:768e1d06155f was 313:768e1d06155f, checked in by David Sharpe, 8 years ago

PEP8

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