source: nagslang/screens/area.py @ 307:c2bbb1e70d6f

Last change on this file since 307:c2bbb1e70d6f was 307:c2bbb1e70d6f, checked in by Neil Muller <drnlmuller@…>, 7 years ago

Rename animate to update and pass seconds, for future fun

File size: 7.7 KB
Line 
1"""Display a game area."""
2
3import pygame
4import pymunk
5import pymunk.pygame_util
6
7from nagslang.constants import (
8    COLLISION_TYPE_WALL, COLLISION_TYPE_PLAYER, CALLBACK_COLLIDERS)
9from nagslang.events import ScreenChange, DoorEvent, FireEvent
10from nagslang.level import Level
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, self.world)
72        self._level.load(self.space)
73        self._drawables = Drawables()
74        self.add_walls()
75        self._add_collision_handlers()
76        self.add_protagonist()
77        self.add_game_objects()
78        sound.play_music("POL-cyber-factory-short.ogg")
79
80    def teardown(self):
81        sound.stop()
82
83    def _collision_pre_solve_handler(self, space, arbiter):
84        gobj = arbiter.shapes[1].physicser.game_object
85        result = gobj.collide_with_protagonist(self.protagonist)
86        # The collision handler must return `True` or `False`. We don't want to
87        # accidentally reject collisions from handlers that return `None`, so
88        # we explicitly check for `False` and treate everything else as `True`.
89        if result is False:
90            return False
91        return True
92
93    def _add_collision_handlers(self):
94        for collision_type in CALLBACK_COLLIDERS:
95            self.space.add_collision_handler(
96                COLLISION_TYPE_PLAYER, collision_type,
97                pre_solve=self._collision_pre_solve_handler)
98
99    def add_walls(self):
100        self.walls = []
101        body = pymunk.Body()
102        body.position = (0, 0)
103        walls = self._level.get_walls()
104        for wall in walls:
105            if len(wall) < 2:
106                # Don't try to add a useless wall
107                continue
108            corners = wall
109            corner = corners[-1]
110            for next_corner in corners:
111                wall = pymunk.Segment(body, corner, next_corner, 5)
112                wall.collision_type = COLLISION_TYPE_WALL
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 = self.world.protagonist
124        self.protagonist.change_space(self.space)
125        self._drawables.add(self.protagonist)
126
127    def handle_event(self, ev):
128        if ev.type == pygame.locals.KEYDOWN:
129            if ev.key == pygame.locals.K_ESCAPE:
130                ScreenChange.post('menu')
131            if ev.key == pygame.locals.K_c:
132                self.protagonist.toggle_form()
133                self.world.transformations += 1
134            if ev.key in (pygame.locals.K_z, pygame.locals.K_LCTRL):
135                self.world.attacks += 1
136                self.protagonist.attack()
137            if ev.key == pygame.locals.K_SPACE:
138                self.protagonist.perform_action()
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)
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, ev.damage,
151                            ev.source_collision_type)
152            self._drawables.add(bullet)
153        self.keys.handle_event(ev)
154
155    def _calc_viewport(self, level_surface, display_surface):
156        level_size = level_surface.get_size()
157        display_size = display_surface.get_size()
158        protagnist_pos = self.protagonist.physicser.get_render_position(
159            level_surface)
160        x_wide = display_size[0] // 2
161        y_wide = display_size[1] // 2
162        if display_size[0] > level_size[0]:
163            x = -(display_size[0] - level_size[0]) // 2
164        elif protagnist_pos[0] < x_wide:
165            x = 0
166        elif protagnist_pos[0] > level_size[0] - x_wide:
167            x = level_size[0] - display_size[0]
168        else:
169            x = protagnist_pos[0] - x_wide
170        if display_size[1] > level_size[1]:
171            y = -(display_size[1] - level_size[1]) // 2
172        elif protagnist_pos[1] < y_wide:
173            y = 0
174        elif protagnist_pos[1] > level_size[1] - y_wide:
175            y = level_size[1] - display_size[1]
176        else:
177            y = protagnist_pos[1] - y_wide
178        return pygame.rect.Rect(x, y, display_size[0], display_size[1])
179
180    def render(self, surface):
181        if self._disable_render:
182            return
183        background = self._level.get_background()
184        mysurface = background.copy()
185        for drawable in self._drawables:
186            drawable.render(mysurface)
187        render_rect = self._calc_viewport(mysurface, surface)
188        surface.blit(mysurface, (0, 0), render_rect)
189        for overlay in self._level.overlay_drawables:
190            if overlay.is_visible():
191                overlay.render(surface, render_rect.topleft)
192        self.render_health_bar(surface)
193
194    def tick_protagonist(self):
195        dx, dy = self.keys.get_direction()
196        self.protagonist.set_direction(dx, dy)
197
198    def tick(self, seconds):
199        super(AreaScreen, self).tick(seconds)
200        self.tick_protagonist()
201        for drawable in self._drawables:
202            drawable.update(seconds)
203            if drawable.remove:
204                self._drawables.remove(drawable)
205
206    def render_health_bar(self, surface, damage_experienced=None):
207        rect = pygame.Rect(50, 500, 110, 50)
208        if damage_experienced:
209            health_box_colour = pygame.color.THECOLORS['red']
210        else:
211            health_box_colour = pygame.color.THECOLORS['white']
212        pygame.draw.rect(surface,  health_box_colour, rect, 0)
213        if self.protagonist.in_human_form():
214            health_colour = pygame.color.THECOLORS['red']
215        else:
216            health_colour = pygame.color.THECOLORS['purple']
217        rect = pygame.Rect(55, 505, self.protagonist.get_health_level(), 40)
218        pygame.draw.rect(surface,  health_colour,
219                         rect, 0)
Note: See TracBrowser for help on using the repository browser.