source: nagslang/screens/area.py@ 265:8a695b8ecd6c

Last change on this file since 265:8a695b8ecd6c was 265:8a695b8ecd6c, checked in by David Sharpe, 8 years ago

Correcting damage application

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