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