ca85884b75a2ccb0e4cbd3aec0494faf5ee4fff1
[koperkapel.git] / koperkapel / scenes / level.py
1 """Render a level"""
2
3 import random
4 from pgzero.constants import keys
5 from pygame import Surface
6 import pygame.locals as pgl
7 from ..loaders.levelloader import levels
8 from .base import (
9     Scene, ChangeSceneEvent, MoveViewportEvent, WorldEvent, defer_to_update)
10 from ..constants import TILE_SIZE, WIDTH, HEIGHT
11 from ..gamelib.items import clone_old_item, create_new_item
12 from ..roaches import build_roach
13 from ..vehicles.base import Vehicle
14 from ..weapons import weapon_by_name
15
16
17 class PlayerStats:
18     def __init__(self, world):
19         roaches = world.roaches
20         self.health = sum(r.health for r in roaches)
21         self.smart = self._count_attr("smart", roaches)
22         self.fast = self._count_attr("fast", roaches)
23         self.strong = self._count_attr("strong", roaches)
24
25     def __str__(self):
26         return "<PlayerStats health=%d smart=%d fast=%d strong=%d>" % (
27             self.health, self.smart, self.fast, self.strong)
28
29     def _count_attr(self, attr, roaches):
30         attrs = [r[attr] for r in roaches]
31         attrs = [a for a in attrs if a]
32         return len(attrs)
33
34
35 class BaseLevelScene(Scene):
36     """ Level scene. """
37
38     def __init__(self):
39         super().__init__()
40         self._level = None
41         self._stats = None
42
43     def enter(self, world):
44         self._level = levels.load(world.level.name)
45         self._tiles = self._level.tiles
46         self._level_layer = 'floor'
47         self._surfaces = {}
48         self._overlay = {}
49         for layer in ['floor', 'tunnels']:
50             self._surfaces[layer] = self._render(layer)
51         self._overlay = self._surfaces['floor'].copy()
52         self._doors = self.actors.add_layer("doors", level=9)
53         self._keypads = self.actors.add_layer("keypads", level=8)
54         self._bullets = self.actors.add_layer("bullets", level=10)
55         # These are already Actors
56         for door in self._level.doors:
57             self._doors.add(door)
58         for keypad in self._level.keypads:
59             self._keypads.add(keypad)
60
61     def _render(self, layer):
62         # We cache the rendered surface to avoid doing a large number
63         # of blits each frame, as that introduces a large performance
64         # overhead.
65         surface = Surface((len(self._tiles[0]) * TILE_SIZE,
66                            len(self._tiles) * TILE_SIZE))
67         layer_key = '%s image' % layer
68         for y, row in enumerate(self._tiles):
69             for x, tile in enumerate(row):
70                 pos = (x * TILE_SIZE, y * TILE_SIZE)
71                 if layer_key not in tile:
72                     # Skip broken tiles for now
73                     continue
74                 surface.blit(tile[layer_key], pos)
75         return surface.convert_alpha()
76
77     def update(self, world, engine, dt):
78         """Fix the door and keypad positions"""
79         super().update(world, engine, dt)
80         for door in self._doors:
81             door.pos = self.calc_offset(
82                 door.game_pos[0] * TILE_SIZE, door.game_pos[1] * TILE_SIZE)
83         for keypad in self._keypads:
84             keypad.pos = self.calc_offset(
85                 keypad.game_pos[0] * TILE_SIZE, keypad.game_pos[1] * TILE_SIZE)
86
87     def draw(self, screen):
88         screen.clear()
89         # Viewport is the position of the screen relative to the
90         # surface. We need the position of the surface relative to
91         # the screen for the blit, so this conversion
92         viewport = self.viewport
93         screen.surface.blit(self._surfaces[self._level_layer], (0, 0),
94                             area=(viewport[0], viewport[1], WIDTH, HEIGHT))
95         if self._level_layer != 'floor':
96             screen.surface.blit(
97                 self._overlay, (0, 0),
98                 area=(viewport[0], viewport[1], WIDTH, HEIGHT),
99                 special_flags=pgl.BLEND_MULT)
100         self.actors.draw(screen)
101
102     def on_key_down(self, key, mod, unicode):
103         if key == keys.ESCAPE:
104             from .menu import MenuScene
105             return [ChangeSceneEvent(MenuScene())]
106
107
108 class GameLevelScene(BaseLevelScene):
109
110     def enter(self, world):
111         self._held_keys = set()
112         if self._level is not None:
113             for generator in self._generators:
114                 generator.unpause()
115             return
116         self._update_player_stats(world)
117         super().enter(world)
118         self._roaches = self.actors.add_layer("roaches", level=10)
119         self._friends = self.actors.add_layer("friendly roaches", level=9)
120         self._items = self.actors.add_layer("items", level=9)
121         self._generators = self.actors.add_layer("enemy generators", level=8)
122         self._enemies = self.actors.add_layer("enemies", level=11)
123         self._vehicle = Vehicle.current(world)
124         self._mode = 'walk'
125         self._angle = 0  # up
126         self._angle_dp = (0, -1)  # up
127         self._init_items()
128         self._init_friendly_roaches()
129         self._init_generators()
130         self._key_rate = 0.2
131         self._last_key_down = 0
132         self._last_dmg = 0
133         return self._init_roaches(world)
134
135     def _init_items(self):
136         for item in self._level.items:
137             self._items.add(item)
138
139     def _init_friendly_roaches(self):
140         for friend in self._level.friends:
141             self._friends.add(friend)
142
143     def exit(self, world):
144         for generator in self._generators:
145             # We don't want these running while we're on other levels, but we
146             # don't want to delete them here either (because of the vehicle
147             # management view)
148             generator.pause()
149
150     def _init_generators(self):
151         for generator in self._level.enemy_generators:
152             self._generators.add(generator)
153             generator.unpause()
154
155     def _init_roaches(self, world):
156         x, y = self._level.start_pos
157         self._level_layer = 'floor'
158         self._avatar = self._vehicle.get_avatar(world)
159         self._set_pos(x, y)
160         self._avatar.pos = (WIDTH // 2, HEIGHT // 2)
161         self._roaches.add(self._avatar)
162         # Fix viewport offset
163         return [
164             MoveViewportEvent((
165                 x * TILE_SIZE - WIDTH // 2,
166                 y * TILE_SIZE - HEIGHT // 2))]
167
168     def _set_pos(self, x, y):
169         self._player_pos = (x, y)
170         # print('At ', (x, y))
171
172     def _can_move(self, x, y):
173         if self._mode == 'walk':
174             if not self._level.enemy_at(x, y):
175                 return self._level.can_walk(x, y, self._level_layer)
176             return False
177         elif self._mode == 'fly':
178             return self._level.can_fly(x, y, self._level_layer)
179         elif self._mode == 'crawl':
180             return self._level.can_crawl(x, y, self._level_layer)
181
182     def _set_angle(self, angle, dp):
183         self._angle = angle
184         self._angle_dp = dp
185         self._avatar.angle = angle
186
187     @defer_to_update
188     def _vehicle_changed(self, world):
189         self._roaches.remove(self._avatar)
190         self._vehicle = Vehicle.current(world)
191         self._avatar = self._vehicle.get_avatar(world)
192         self._avatar.pos = (WIDTH // 2, HEIGHT // 2)
193         self._roaches.add(self._avatar)
194         self._set_angle(self._angle, self._angle_dp)
195
196     @defer_to_update
197     def _add_roach(self, world):
198         world.roaches.append(build_roach(world))
199         self._vehicle_changed()
200
201     @defer_to_update
202     def _damage_player(self, world):
203         if not world.roaches:
204             # Skip out if we're already dead
205             return
206         roach = random.choice(world.roaches)
207         roach.health -= self._last_dmg
208         self._last_dmg = 0
209         if roach.health < 0:
210             index = [x.name for x in world.roaches].index(roach.name)
211             world.roaches.pop(index)
212             # We can't check for empty, because updates will be processed later
213             if len(world.roaches) > 1:
214                 self._vehicle_changed()
215
216     @defer_to_update
217     def _gain_item(self, world, item):
218         if item.item_type == "serum":
219             world.serums.append(item.item_data["serum"])
220         elif item.item_type == "weapon":
221             old_weapon = world.weapons.current
222             world.weapons.current = item.item_data["weapon"]
223             if old_weapon != "spit":
224                 clone = clone_old_item(item, weapon=old_weapon)
225                 self._level.items.append(clone)
226                 self._items.add(clone)
227         self._vehicle_changed()
228
229     def _hit_enemy(self, enemy, weapon):
230         enemy.health -= weapon.damage
231         if enemy.health <= 0:
232             self._level.remove_enemy(enemy)
233             self._enemies.remove(enemy)
234
235     def _fire_bullet(self, bullet, pos, dp, angle):
236         if len(self._bullets) >= 10:
237             return
238         bullet.game_pos = pos
239         bullet.game_dp = dp
240         bullet.dt = 0
241         bullet.level_layer = self._level_layer
242         bullet.angle = angle
243         self._bullets.add(bullet)
244
245     def _check_for_bullet_hits(self):
246         for bullet in list(self._bullets):
247             for enemy in list(self._enemies):
248                 if enemy.collidepoint(bullet.pos):
249                     self._hit_enemy(enemy, bullet.weapon)
250                     self._bullets.remove(bullet)
251
252     def _update_bullet(self, bullet, dt):
253         bullet.dt += dt
254         if bullet.dt > 0.1:
255             bullet.dt = 0
256             bullet.game_pos = pos = (
257                 bullet.game_pos[0] + bullet.game_dp[0],
258                 bullet.game_pos[1] + bullet.game_dp[1])
259             if not self._level.can_bullet(pos[0], pos[1], bullet.level_layer):
260                 self._bullets.remove(bullet)
261
262     @defer_to_update
263     def _fire_weapon(self, world):
264         weapon = weapon_by_name(world.weapons.current)
265         weapon.play_sound()
266         if weapon.bullet_range > 0:
267             self._fire_bullet(
268                 weapon.assemble_bullet(), self._player_pos, self._angle_dp,
269                 self._angle)
270         else:
271             # melee
272             pos, dp = self._player_pos, self._angle_dp
273             pos = (pos[0] + dp[0], pos[1] + dp[1])
274             enemy = self._level.get_enemy(pos[0], pos[1])
275             if enemy:
276                 self._hit_enemy(enemy, weapon)
277
278     @defer_to_update
279     def _change_vehicle(self, world):
280         x, y = self._player_pos
281
282         old_vehicle = world.vehicles.current
283
284         item = self._level.item_at(x, y)
285
286         if item and item.item_type == "vehicle":
287             world.vehicles.current = item.item_data["vehicle"]
288             self._level.remove_item(item)
289             self._items.remove(item)
290         else:
291             world.vehicles.current = "walking"
292
293         if old_vehicle != "walking":
294             dropped_vehicle = create_new_item(
295                 "vehicle", (x, y), vehicle=old_vehicle)
296             self._level.items.append(dropped_vehicle)
297             self._items.add(dropped_vehicle)
298
299         self._vehicle_changed()
300
301     def update(self, world, engine, dt):
302         if not world.roaches:
303             # Catch death here
304             from .menu import MenuScene
305             return [ChangeSceneEvent(MenuScene())]
306         super().update(world, engine, dt)
307         events = world.pop_events()
308         for friend in self._friends:
309             friend.pos = self.calc_offset(
310                 friend.game_pos[0] * TILE_SIZE, friend.game_pos[1] * TILE_SIZE)
311         for item in self._items:
312             item.pos = self.calc_offset(
313                 item.game_pos[0] * TILE_SIZE, item.game_pos[1] * TILE_SIZE)
314         self._check_enemies(dt)
315         for enemy in self._enemies:
316             enemy.pos = self.calc_offset(
317                 enemy.game_pos[0] * TILE_SIZE, enemy.game_pos[1] * TILE_SIZE)
318         for bullet in list(self._bullets):
319             self._update_bullet(bullet, dt)
320             bullet.pos = self.calc_offset(
321                 bullet.game_pos[0] * TILE_SIZE + (TILE_SIZE // 2),
322                 bullet.game_pos[1] * TILE_SIZE + (TILE_SIZE // 2))
323         self._check_for_bullet_hits()
324         self._update_player_stats(world)
325         more = self._check_held_keys(dt)
326         if more:
327             events.extend(more)
328         return events
329
330     def _update_player_stats(self, world):
331         self._stats = PlayerStats(world)
332
333     def _check_enemies(self, dt):
334         if len(self._level.enemies) != len(self._enemies):
335             # New nemy has spawned
336             for enemy in self._level.enemies:
337                 if enemy not in self._enemies:
338                     self._enemies.add(enemy)
339         for enemy in self._enemies:
340             dmg = enemy.attack(self._player_pos, self._level_layer, dt)
341             if dmg is not None:
342                 self._last_dmg += dmg
343         if self._last_dmg:
344             self._damage_player()
345
346     def _check_held_keys(self, dt):
347         for key in self._held_keys:
348             self._last_key_down += dt
349             if key in (keys.DOWN, keys.UP, keys.LEFT, keys.RIGHT):
350                 return self._movement_key(key, dt)
351             elif key == keys.X:
352                 return self._fire_key(dt)
353
354     def _movement_key(self, key, dt):
355         x, y = self._player_pos
356         for k, dp, angle in (
357             (keys.DOWN, (0, 1), 180),
358             (keys.UP, (0, -1), 0),
359             (keys.LEFT, (-1, 0), 90),
360             (keys.RIGHT, (1, 0), -90),
361         ):
362             if key == k:
363                 if (self._angle == angle and
364                         self._last_key_down > self._key_rate):
365                     nx, ny = x + dp[0], y + dp[1]
366                     if self._can_move(nx, ny):
367                         self._set_pos(nx, ny)
368                         offset = (TILE_SIZE * dp[0], TILE_SIZE * dp[1])
369                         self._set_angle(angle, dp)
370                         self._last_key_down = 0
371                         return [MoveViewportEvent(offset)]
372                 else:
373                     # just turn
374                     self._set_angle(angle, dp)
375
376     def _activate_key(self):
377         x, y = self._player_pos
378         if self._level.is_grate(x, y):
379             if (self._level_layer == 'floor' and
380                     self._level.can_crawl(x, y, 'floor')):
381                 if self._level.can_crawl(x, y, 'tunnels'):
382                     self._level_layer = 'tunnels'
383                     self._mode = 'crawl'
384             elif self._level.can_crawl(x, y, 'floor'):
385                 # Must be in the tunnels already
386                 self._level_layer = 'floor'
387                 self._mode = 'walk'
388         elif self._level.is_keypad(x, y):
389             self._level.press_keypad(x, y, self._stats.smart)
390         elif self._level.friend_at(x, y):
391             friend = self._level.friend_at(x, y)
392             self._level.remove_friend(friend)
393             self._friends.remove(friend)
394             self._add_roach()
395         elif self._level.item_at(x, y):
396             item = self._level.item_at(x, y)
397             if item.item_type != "vehicle":
398                 self._level.remove_item(item)
399                 self._items.remove(item)
400                 self._gain_item(item)
401         elif self._level.is_exit(x, y):
402             next_level = self._level.get_exit_level()
403             return [
404                 WorldEvent('set', {'level.name': next_level}),
405                 ChangeSceneEvent(GameLevelScene())]
406
407     def _fire_key(self, dt):
408         if self._last_key_down > self._key_rate:
409             self._last_key_down = 0
410             self._fire_weapon()
411
412     def _vehicle_management_key(self):
413         from .roach_management import RoachesScene
414         return [ChangeSceneEvent(RoachesScene(level_scene=self))]
415
416     def on_key_down(self, key, mod, unicode):
417         x, y = self._player_pos
418         if key in (keys.DOWN, keys.UP, keys.LEFT, keys.RIGHT):
419             firing = (keys.X in self._held_keys)
420             self._held_keys.clear()
421             self._held_keys.add(key)
422             if firing:
423                 self._held_keys.add(keys.X)
424             # We do this so pressing the key has an instant effect, and can
425             # then be held
426             self._last_key_down = self._key_rate + 0.01
427             return self._movement_key(key, 0.01)
428         elif key == keys.C:
429             return self._activate_key()
430         elif key == keys.X:
431             self._held_keys.clear()
432             self._held_keys.add(key)
433             self._last_key_down = self._key_rate + 0.01
434             return self._fire_key(0.01)
435         elif key == keys.V:
436             return self._change_vehicle()
437         elif key == keys.Z:
438             return self._vehicle_management_key()
439         return super(GameLevelScene, self).on_key_down(key, mod, unicode)
440
441     def on_key_up(self, key, mode):
442         self._held_keys.discard(key)
443         self._last_key_down = 0