source: nagslang/screens/area.py @ 272:933c2f9371ca

Last change on this file since 272:933c2f9371ca was 272:933c2f9371ca, checked in by Simon Cross <hodgestar@…>, 7 years ago

Stop music when the level ends.

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