source: nagslang/screens/area.py@ 266:9d05f0c4bca3

Last change on this file since 266:9d05f0c4bca3 was 266:9d05f0c4bca3, checked in by David Sharpe, 8 years ago

Pep8

File size: 7.5 KB
Line 
1"""Display a game area."""
2
3import pygame
4import pymunk
5import pymunk.pygame_util
6
7from nagslang.constants import COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS
8from nagslang.events import ScreenChange, DoorEvent, FireEvent
9from nagslang.level import Level
10from nagslang.protagonist import Protagonist
11from nagslang.screens.base import Screen
12from nagslang.game_object import Bullet
13
14
15class ControlKeys(object):
16 direction_keys = {
17 (0, 1): set([pygame.locals.K_UP, pygame.locals.K_w]),
18 (0, -1): set([pygame.locals.K_DOWN, pygame.locals.K_s]),
19 (-1, 0): set([pygame.locals.K_LEFT, pygame.locals.K_a]),
20 (1, 0): set([pygame.locals.K_RIGHT, pygame.locals.K_d]),
21 }
22
23 def __init__(self):
24 self.keys_down = set()
25
26 def key_down(self, key):
27 self.keys_down.add(key)
28
29 def key_up(self, key):
30 self.keys_down.discard(key)
31
32 def handle_event(self, ev):
33 if ev.type == pygame.locals.KEYDOWN:
34 self.key_down(ev.key)
35 elif ev.type == pygame.locals.KEYUP:
36 self.key_up(ev.key)
37
38 def get_direction(self):
39 dx, dy = 0, 0
40 for (tx, ty), keys in self.direction_keys.iteritems():
41 if self.keys_down & keys:
42 dx += tx
43 dy += ty
44 return (dx, dy)
45
46
47class Drawables(object):
48 def __init__(self):
49 self._drawables = {}
50
51 def add(self, drawable):
52 self._drawables.setdefault(drawable.zorder, []).append(drawable)
53
54 def remove(self, drawable):
55 self._drawables[drawable.zorder].remove(drawable)
56
57 def get_drawables(self):
58 for zorder in sorted(self._drawables):
59 for drawable in self._drawables[zorder]:
60 yield drawable
61
62 __iter__ = get_drawables
63
64
65class AreaScreen(Screen):
66
67 def setup(self):
68 self._disable_render = False # Avoid redrawing on scene changes
69 self.keys = ControlKeys()
70 self._level = Level(self.name)
71 self._level.load(self.space)
72 self._drawables = Drawables()
73 self.add_walls()
74 self._add_collision_handlers()
75 if self.protagonist is not None:
76 # We do things this way to avoid extra pymunk
77 # juggling to move objects between spaces
78 old_protagonist = self.protagonist
79 self.add_protagonist()
80 self.protagonist.copy_state(old_protagonist)
81 else:
82 self.add_protagonist()
83 self.add_game_objects()
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 corners = wall
108 corner = corners[-1]
109 for next_corner in corners:
110 wall = pymunk.Segment(body, corner, next_corner, 5)
111 wall.elasticity = 1.0
112 self.walls.append(wall)
113 corner = next_corner
114 self.space.add(*self.walls)
115
116 def add_game_objects(self):
117 for drawable in self._level.drawables:
118 self._drawables.add(drawable)
119
120 def add_protagonist(self):
121 self.protagonist = Protagonist(self.space, (350, 300))
122 self._drawables.add(self.protagonist)
123
124 def handle_event(self, ev):
125 if ev.type == pygame.locals.KEYDOWN:
126 if ev.key == pygame.locals.K_ESCAPE:
127 ScreenChange.post('menu')
128 if ev.key == pygame.locals.K_c:
129 self.protagonist.toggle_form()
130 self.world.transformations += 1
131 if ev.key == pygame.locals.K_SPACE:
132 self.world.attacks += 1
133 self.protagonist.attack()
134 elif DoorEvent.matches(ev):
135 self.protagonist.set_position(ev.dest_pos)
136 if ev.destination != self.name:
137 # Go to anther screen
138 self._disable_render = True
139 self.world.rooms += 1
140 ScreenChange.post(ev.destination, self.protagonist)
141 return
142 # else we're teleporting within the screen, and just the
143 # position change is enough
144 elif FireEvent.matches(ev):
145 bullet = Bullet(self.space, ev.source, ev.impulse)
146 self._drawables.add(bullet)
147 self.keys.handle_event(ev)
148
149 def _calc_viewport(self, level_surface, display_surface):
150 level_size = level_surface.get_size()
151 display_size = display_surface.get_size()
152 protagnist_pos = self.protagonist.physicser.get_render_position(
153 level_surface)
154 x_wide = display_size[0] // 2
155 y_wide = display_size[1] // 2
156 if display_size[0] > level_size[0]:
157 x = -(display_size[0] - level_size[0]) // 2
158 elif protagnist_pos[0] < x_wide:
159 x = 0
160 elif protagnist_pos[0] > level_size[0] - x_wide:
161 x = level_size[0] - display_size[0]
162 else:
163 x = protagnist_pos[0] - x_wide
164 if display_size[1] > level_size[1]:
165 y = -(display_size[1] - level_size[1]) // 2
166 elif protagnist_pos[1] < y_wide:
167 y = 0
168 elif protagnist_pos[1] > level_size[1] - y_wide:
169 y = level_size[1] - display_size[1]
170 else:
171 y = protagnist_pos[1] - y_wide
172 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
173
174 def render(self, surface):
175 if self._disable_render:
176 return
177 background = self._level.get_background()
178 mysurface = background.copy()
179 for drawable in self._drawables:
180 drawable.render(mysurface)
181 render_rect = self._calc_viewport(mysurface, surface)
182 surface.blit(mysurface, (0, 0), render_rect)
183 for overlay in self._level.overlay_drawables:
184 if overlay.is_visible():
185 overlay.render(surface, render_rect.topleft)
186 self.render_health_bar(surface)
187
188 def tick_protagonist(self):
189 dx, dy = self.keys.get_direction()
190 self.protagonist.set_direction(dx, dy)
191
192 def tick(self, seconds):
193 self.tick_protagonist()
194 for drawable in self._drawables:
195 drawable.animate()
196
197 super(AreaScreen, self).tick(seconds)
198
199 def render_health_bar(self, surface, damage_experienced=None):
200 rect = pygame.Rect(50, 500, 110, 50)
201 if damage_experienced:
202 health_box_colour = pygame.color.THECOLORS['red']
203 else:
204 health_box_colour = pygame.color.THECOLORS['white']
205 pygame.draw.rect(surface, health_box_colour, rect, 0)
206 if self.protagonist.in_human_form():
207 health_colour = pygame.color.THECOLORS['red']
208 else:
209 health_colour = pygame.color.THECOLORS['purple']
210 rect = pygame.Rect(55, 505, self.protagonist.get_health_level(), 40)
211 pygame.draw.rect(surface, health_colour,
212 rect, 0)
Note: See TracBrowser for help on using the repository browser.