source: nagslang/screens/area.py@ 293:47226c661ae2

Last change on this file since 293:47226c661ae2 was 293:47226c661ae2, checked in by Stefano Rivera <stefano@…>, 8 years ago

Bullets that mostly die when they hit things

File size: 7.6 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.screens.base import Screen
11from nagslang.game_object import Bullet
12from nagslang.sound import sound
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, self.world)
71 self._level.load(self.space)
72 self._drawables = Drawables()
73 self.add_walls()
74 self._add_collision_handlers()
75 self.add_protagonist()
76 self.add_game_objects()
77 sound.play_music("POL-cyber-factory-short.ogg")
78
79 def teardown(self):
80 sound.stop()
81
82 def _collision_pre_solve_handler(self, space, arbiter):
83 gobj = arbiter.shapes[1].physicser.game_object
84 result = gobj.collide_with_protagonist(self.protagonist)
85 # The collision handler must return `True` or `False`. We don't want to
86 # accidentally reject collisions from handlers that return `None`, so
87 # we explicitly check for `False` and treate everything else as `True`.
88 if result is False:
89 return False
90 return True
91
92 def _add_collision_handlers(self):
93 for collision_type in CALLBACK_COLLIDERS:
94 self.space.add_collision_handler(
95 COLLISION_TYPE_PLAYER, collision_type,
96 pre_solve=self._collision_pre_solve_handler)
97
98 def add_walls(self):
99 self.walls = []
100 body = pymunk.Body()
101 body.position = (0, 0)
102 walls = self._level.get_walls()
103 for wall in walls:
104 if len(wall) < 2:
105 # Don't try to add a useless wall
106 continue
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 = self.world.protagonist
122 self.protagonist.change_space(self.space)
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 in (pygame.locals.K_z, pygame.locals.K_LCTRL):
133 self.world.attacks += 1
134 self.protagonist.attack()
135 if ev.key == pygame.locals.K_SPACE:
136 self.protagonist.perform_action()
137 elif DoorEvent.matches(ev):
138 self.protagonist.set_position(ev.dest_pos)
139 if ev.destination != self.name:
140 # Go to anther screen
141 self._disable_render = True
142 self.world.rooms += 1
143 ScreenChange.post(ev.destination)
144 return
145 # else we're teleporting within the screen, and just the
146 # position change is enough
147 elif FireEvent.matches(ev):
148 bullet = Bullet(self.space, ev.source, ev.impulse,
149 ev.source_collision_type)
150 self._drawables.add(bullet)
151 self.keys.handle_event(ev)
152
153 def _calc_viewport(self, level_surface, display_surface):
154 level_size = level_surface.get_size()
155 display_size = display_surface.get_size()
156 protagnist_pos = self.protagonist.physicser.get_render_position(
157 level_surface)
158 x_wide = display_size[0] // 2
159 y_wide = display_size[1] // 2
160 if display_size[0] > level_size[0]:
161 x = -(display_size[0] - level_size[0]) // 2
162 elif protagnist_pos[0] < x_wide:
163 x = 0
164 elif protagnist_pos[0] > level_size[0] - x_wide:
165 x = level_size[0] - display_size[0]
166 else:
167 x = protagnist_pos[0] - x_wide
168 if display_size[1] > level_size[1]:
169 y = -(display_size[1] - level_size[1]) // 2
170 elif protagnist_pos[1] < y_wide:
171 y = 0
172 elif protagnist_pos[1] > level_size[1] - y_wide:
173 y = level_size[1] - display_size[1]
174 else:
175 y = protagnist_pos[1] - y_wide
176 return pygame.rect.Rect(x, y, display_size[0], display_size[1])
177
178 def render(self, surface):
179 if self._disable_render:
180 return
181 background = self._level.get_background()
182 mysurface = background.copy()
183 for drawable in self._drawables:
184 drawable.render(mysurface)
185 render_rect = self._calc_viewport(mysurface, surface)
186 surface.blit(mysurface, (0, 0), render_rect)
187 for overlay in self._level.overlay_drawables:
188 if overlay.is_visible():
189 overlay.render(surface, render_rect.topleft)
190 self.render_health_bar(surface)
191
192 def tick_protagonist(self):
193 dx, dy = self.keys.get_direction()
194 self.protagonist.set_direction(dx, dy)
195
196 def tick(self, seconds):
197 self.tick_protagonist()
198 for drawable in self._drawables:
199 drawable.animate()
200 if drawable.remove:
201 self._drawables.remove(drawable)
202
203 super(AreaScreen, self).tick(seconds)
204
205 def render_health_bar(self, surface, damage_experienced=None):
206 rect = pygame.Rect(50, 500, 110, 50)
207 if damage_experienced:
208 health_box_colour = pygame.color.THECOLORS['red']
209 else:
210 health_box_colour = pygame.color.THECOLORS['white']
211 pygame.draw.rect(surface, health_box_colour, rect, 0)
212 if self.protagonist.in_human_form():
213 health_colour = pygame.color.THECOLORS['red']
214 else:
215 health_colour = pygame.color.THECOLORS['purple']
216 rect = pygame.Rect(55, 505, self.protagonist.get_health_level(), 40)
217 pygame.draw.rect(surface, health_colour,
218 rect, 0)
Note: See TracBrowser for help on using the repository browser.