source: nagslang/screens/area.py@ 258:083053422a84

Last change on this file since 258:083053422a84 was 258:083053422a84, checked in by David Sharpe, 8 years ago

Added collision damage with enemies.

File size: 7.3 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, \
8 COLLISION_TYPE_ENEMY
9from nagslang.events import ScreenChange, DoorEvent
10from nagslang.level import Level
11from nagslang.protagonist import Protagonist
12from nagslang.screens.base import Screen
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 if arbiter.shapes[1].collision_type == COLLISION_TYPE_ENEMY:
89 self.protagonist.lose_health(15)
90 # The collision handler must return `True` or `False`. We don't want to
91 # accidentally reject collisions from handlers that return `None`, so
92 # we explicitly check for `False` and treate everything else as `True`.
93 if result is False:
94 return False
95 return True
96
97 def _add_collision_handlers(self):
98 for collision_type in CALLBACK_COLLIDERS:
99 self.space.add_collision_handler(
100 COLLISION_TYPE_PLAYER, collision_type,
101 pre_solve=self._collision_pre_solve_handler)
102
103 def add_walls(self):
104 self.walls = []
105 body = pymunk.Body()
106 body.position = (0, 0)
107 walls = self._level.get_walls()
108 for wall in walls:
109 corners = wall
110 corner = corners[-1]
111 for next_corner in corners:
112 wall = pymunk.Segment(body, corner, next_corner, 5)
113 wall.elasticity = 1.0
114 self.walls.append(wall)
115 corner = next_corner
116 self.space.add(*self.walls)
117
118 def add_game_objects(self):
119 for drawable in self._level.drawables:
120 self._drawables.add(drawable)
121
122 def add_protagonist(self):
123 self.protagonist = Protagonist(self.space, (350, 300))
124 self._drawables.add(self.protagonist)
125
126 def handle_event(self, ev):
127 if ev.type == pygame.locals.KEYDOWN:
128 if ev.key == pygame.locals.K_ESCAPE:
129 ScreenChange.post('menu')
130 if ev.key == pygame.locals.K_c:
131 self.protagonist.toggle_form()
132 self.world.transformations += 1
133 elif DoorEvent.matches(ev):
134 self.protagonist.set_position(ev.dest_pos)
135 if ev.destination != self.name:
136 # Go to anther screen
137 self._disable_render = True
138 self.world.rooms += 1
139 ScreenChange.post(ev.destination, self.protagonist)
140 return
141 # else we're teleporting within the screen, and just the
142 # position change is enough
143 self.keys.handle_event(ev)
144
145 def _calc_viewport(self, level_surface, display_surface):
146 level_size = level_surface.get_size()
147 display_size = display_surface.get_size()
148 protagnist_pos = self.protagonist.physicser.get_render_position(
149 level_surface)
150 x_wide = display_size[0] // 2
151 y_wide = display_size[1] // 2
152 if display_size[0] > level_size[0]:
153 x = -(display_size[0] - level_size[0]) // 2
154 elif protagnist_pos[0] < x_wide:
155 x = 0
156 elif protagnist_pos[0] > level_size[0] - x_wide:
157 x = level_size[0] - display_size[0]
158 else:
159 x = protagnist_pos[0] - x_wide
160 if display_size[1] > level_size[1]:
161 y = -(display_size[1] - level_size[1]) // 2
162 elif protagnist_pos[1] < y_wide:
163 y = 0
164 elif protagnist_pos[1] > level_size[1] - y_wide:
165 y = level_size[1] - display_size[1]
166 else:
167 y = protagnist_pos[1] - y_wide
168 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
169
170 def render(self, surface):
171 if self._disable_render:
172 return
173 background = self._level.get_background()
174 mysurface = background.copy()
175 for drawable in self._drawables:
176 drawable.render(mysurface)
177 render_rect = self._calc_viewport(mysurface, surface)
178 surface.blit(mysurface, (0, 0), render_rect)
179 for overlay in self._level.overlay_drawables:
180 if overlay.is_visible():
181 overlay.render(surface, render_rect.topleft)
182 self.render_health_bar(surface)
183
184 def tick_protagonist(self):
185 dx, dy = self.keys.get_direction()
186 self.protagonist.set_direction(dx, dy)
187
188 def tick(self, seconds):
189 self.tick_protagonist()
190 for drawable in self._drawables:
191 drawable.animate()
192
193 super(AreaScreen, self).tick(seconds)
194
195 def render_health_bar(self, surface, damage_experienced=None):
196 rect = pygame.Rect(50, 500, 110, 50)
197 if damage_experienced:
198 health_box_colour = pygame.color.THECOLORS['red']
199 else:
200 health_box_colour = pygame.color.THECOLORS['white']
201 pygame.draw.rect(surface, health_box_colour, rect, 0)
202 if self.protagonist.in_human_form():
203 health_colour = pygame.color.THECOLORS['red']
204 else:
205 health_colour = pygame.color.THECOLORS['purple']
206 rect = pygame.Rect(55, 505, self.protagonist.get_health_level(), 40)
207 pygame.draw.rect(surface, health_colour,
208 rect, 0)
Note: See TracBrowser for help on using the repository browser.