game_pos should be a tuple.
[koperkapel.git] / koperkapel / scenes / level.py
1 """Render a level"""
2
3 from pgzero.constants import keys
4 from pygame import Surface
5 import pygame.locals as pgl
6 from ..loaders.levelloader import levels
7 from .base import Scene, ChangeSceneEvent, MoveViewportEvent, WorldEvent, defer_to_update
8 from ..constants import TILE_SIZE, WIDTH, HEIGHT
9 from ..roaches import build_roach
10 from ..vehicles.base import Vehicle
11
12
13 class BaseLevelScene(Scene):
14     """ Level scene. """
15
16     def __init__(self):
17         super().__init__()
18         self._level = None
19
20     def enter(self, world):
21         self._level = levels.load(world.level.name)
22         self._tiles = self._level.tiles
23         self._level_layer = 'floor'
24         self._surfaces = {}
25         self._overlay = {}
26         for layer in ['floor', 'tunnels']:
27             self._surfaces[layer] = self._render(layer)
28         self._overlay = self._surfaces['floor'].copy()
29         self._doors = self.actors.add_layer("doors", level=9)
30         self._keypads = self.actors.add_layer("keypads", level=8)
31         # These are already Actors
32         for door in self._level.doors:
33             self._doors.add(door)
34         for keypad in self._level.keypads:
35             self._keypads.add(keypad)
36
37     def _render(self, layer):
38         # We cache the rendered surface to avoid doing a large number
39         # of blits each frame, as that introduces a large performance
40         # overhead.
41         surface = Surface((len(self._tiles[0]) * TILE_SIZE,
42                            len(self._tiles) * TILE_SIZE))
43         layer_key = '%s image' % layer
44         for y, row in enumerate(self._tiles):
45             for x, tile in enumerate(row):
46                 pos = (x * TILE_SIZE, y * TILE_SIZE)
47                 if layer_key not in tile:
48                     # Skip broken tiles for now
49                     continue
50                 surface.blit(tile[layer_key], pos)
51         return surface.convert_alpha()
52
53     def update(self, world, engine, dt):
54         """Fix the door and keypad positions"""
55         super().update(world, engine, dt)
56         for door in self._doors:
57             door.pos = self.calc_offset(
58                 door.game_pos[0] * TILE_SIZE, door.game_pos[1] * TILE_SIZE)
59         for keypad in self._keypads:
60             keypad.pos = self.calc_offset(
61                 keypad.game_pos[0] * TILE_SIZE, keypad.game_pos[1] * TILE_SIZE)
62
63     def draw(self, screen):
64         screen.clear()
65         # Viewport is the position of the screen relative to the
66         # surface. We need the position of the surface relative to
67         # the screen for the blit, so this conversion
68         viewport = self.viewport
69         screen.surface.blit(self._surfaces[self._level_layer], (0, 0),
70                             area=(viewport[0], viewport[1], WIDTH, HEIGHT))
71         if self._level_layer != 'floor':
72             screen.surface.blit(
73                 self._overlay, (0, 0),
74                 area=(viewport[0], viewport[1], WIDTH, HEIGHT),
75                 special_flags=pgl.BLEND_MULT)
76         self.actors.draw(screen)
77
78     def on_key_down(self, key, mod, unicode):
79         if key == keys.ESCAPE:
80             from .menu import MenuScene
81             return [ChangeSceneEvent(MenuScene())]
82
83
84 class GameLevelScene(BaseLevelScene):
85
86     def enter(self, world):
87         if self._level is not None:
88             for generator in self._generators:
89                 generator.unpause()
90             return
91         super().enter(world)
92         self._roaches = self.actors.add_layer("roaches", level=10)
93         self._friends = self.actors.add_layer("friendly roaches", level=9)
94         self._items = self.actors.add_layer("items", level=9)
95         self._generators = self.actors.add_layer("enemy generators", level=8)
96         self._enemies = self.actors.add_layer("enemies", level=7)
97         self._vehicle = Vehicle.current(world)
98         self._mode = 'walk'
99         self._angle = 0
100         self._init_items()
101         self._init_friendly_roaches()
102         self._init_generators()
103         return self._init_roaches(world)
104
105     def _init_items(self):
106         for item in self._level.items:
107             self._items.add(item)
108
109     def _init_friendly_roaches(self):
110         for friend in self._level.friends:
111             self._friends.add(friend)
112
113     def exit(self, world):
114         for generator in self._generators:
115             # We don't want these running while we're on other levels, but we don't want to delete them
116             # here either (because of the vehicle management view)
117             generator.pause()
118
119     def _init_generators(self):
120         for generator in self._level.enemy_generators:
121             self._generators.add(generator)
122             generator.unpause()
123
124     def _init_roaches(self, world):
125         x, y = self._level.start_pos
126         self._level_layer = 'floor'
127         self._avatar = self._vehicle.get_avatar(world)
128         self._set_pos(x, y)
129         self._avatar.pos = (WIDTH // 2, HEIGHT // 2)
130         self._roaches.add(self._avatar)
131         # Fix viewport offset
132         return [
133             MoveViewportEvent((
134                 x * TILE_SIZE - WIDTH // 2,
135                 y * TILE_SIZE - HEIGHT // 2))]
136
137     def _set_pos(self, x, y):
138         self._player_pos = (x, y)
139         # print('At ', (x, y))
140
141     def _can_move(self, x, y):
142         if self._mode == 'walk':
143             return self._level.can_walk(x, y, self._level_layer)
144         elif self._mode == 'fly':
145             return self._level.can_fly(x, y, self._level_layer)
146         elif self._mode == 'crawl':
147             return self._level.can_crawl(x, y, self._level_layer)
148
149     def _set_angle(self, angle):
150         self._angle = angle
151         self._avatar.angle = angle
152
153     @defer_to_update
154     def _vehicle_changed(self, world):
155         self._roaches.remove(self._avatar)
156         self._vehicle = Vehicle.current(world)
157         self._avatar = self._vehicle.get_avatar(world)
158         self._avatar.pos = (WIDTH // 2, HEIGHT // 2)
159         self._roaches.add(self._avatar)
160         self._set_angle(self._angle)
161
162     @defer_to_update
163     def _add_roach(self, world):
164         world.roaches.append(build_roach(world))
165         self._vehicle_changed()
166
167     @defer_to_update
168     def _change_vehicle(self, world):
169         vehicle = Vehicle.random()
170         world.vehicles.current = vehicle
171         self._vehicle_changed()
172
173     def update(self, world, engine, dt):
174         super().update(world, engine, dt)
175         events = world.pop_events()
176         for friend in self._friends:
177             friend.pos = self.calc_offset(
178                 friend.game_pos[0] * TILE_SIZE, friend.game_pos[1] * TILE_SIZE)
179         for item in self._items:
180             item.pos = self.calc_offset(
181                 item.game_pos[0] * TILE_SIZE, item.game_pos[1] * TILE_SIZE)
182         return events
183
184     def _movement_key(self, key):
185         x, y = self._player_pos
186         for k, dp, angle in (
187             (keys.DOWN, (0, 1), 180),
188             (keys.UP, (0, -1), 0),
189             (keys.LEFT, (-1, 0), 90),
190             (keys.RIGHT, (1, 0), -90),
191         ):
192             if key == k:
193                 nx, ny = x + dp[0], y + dp[1]
194                 if self._can_move(nx, ny):
195                     self._set_pos(nx, ny)
196                     offset = (TILE_SIZE * dp[0], TILE_SIZE * dp[1])
197                     self._set_angle(angle)
198                     return [MoveViewportEvent(offset)]
199
200     def _activate_key(self):
201         x, y = self._player_pos
202         if self._level.is_grate(x, y):
203             if (self._level_layer == 'floor' and
204                     self._level.can_crawl(x, y, 'floor')):
205                 if self._level.can_crawl(x, y, 'tunnels'):
206                     self._level_layer = 'tunnels'
207                     self._mode = 'crawl'
208             elif self._level.can_crawl(x, y, 'floor'):
209                 # Must be in the tunnels already
210                 self._level_layer = 'floor'
211                 self._mode = 'walk'
212         elif self._level.is_keypad(x, y):
213             self._level.press_keypad(x, y, self._roaches)
214         elif self._level.is_on_friend(x, y):
215             friend = self._level.remove_friend(x, y)
216             self._friends.remove(friend)
217             self._add_roach()
218         elif self._level.is_exit(x, y):
219             next_level = self._level.get_exit_level()
220             return [WorldEvent('set', {'level.name': next_level}), ChangeSceneEvent(GameLevelScene())]
221
222     def _fire_key(self):
223         print('Boom')
224
225     def _vehicle_management_key(self):
226         from .roach_management import RoachesScene
227         return [ChangeSceneEvent(RoachesScene(level_scene=self))]
228
229     def on_key_down(self, key, mod, unicode):
230         x, y = self._player_pos
231         if key in (keys.DOWN, keys.UP, keys.LEFT, keys.RIGHT):
232             return self._movement_key(key)
233         elif key == keys.C:
234             return self._activate_key()
235         elif key == keys.X:
236             return self._fire_key()
237         elif key == keys.V:
238             return self._change_vehicle()
239         elif key == keys.Z:
240             return self._vehicle_management_key()
241         return super(GameLevelScene, self).on_key_down(key, mod, unicode)