Add roach_by_name helper.
[koperkapel.git] / koperkapel / roaches.py
1 """ Tools for creating roach actors. """
2
3 import random
4 from pgzero.clock import each_tick
5 from pgzero.loaders import images
6 from pygame.constants import BLEND_RGBA_MULT
7 from .actors.orientatedsurf import OrientatedSurfActor
8 from .serums import roach_serum_color
9
10
11 def roach_by_name(world, roach_name):
12     roaches = [r for r in world.roaches if r.name == roach_name]
13     if not roaches:
14         return None
15     return roaches[0]
16
17
18 class RoachActor(OrientatedSurfActor):
19     def __init__(self, frames):
20         self._frames = frames
21         self._frame = random.randint(0, len(frames) - 1)
22         self._dt = 0
23         self._cycle_dt = 0.2
24         each_tick(self.update)
25         super().__init__(surf=frames[self._frame], angle=0)
26
27     def update(self, dt):
28         self._dt += dt
29         while self._dt > self._cycle_dt:
30             self._dt -= self._cycle_dt
31             self._frame += 1
32             self._frame %= len(self._frames)
33         self.surf = self._frames[self._frame]
34
35
36 class RoachFactory:
37
38     def __init__(self, suffix, frames=4):
39         self.suffix = suffix
40         self.frames = 4
41
42     def assemble_frame(self, i, color, roach_data):
43         roach = images.load("roach%s/roach_%d" % (self.suffix, i + 1))
44         eyes = images.load("roach%s/eyes_%d" % (self.suffix, i + 1))
45         frame = roach.copy()
46         frame.fill(color, None, BLEND_RGBA_MULT)
47         frame.blit(eyes, (0, 0))
48         return frame
49
50     def assemble(self, roach_data):
51         color = roach_serum_color(roach_data)
52         frames = [
53             self.assemble_frame(i, color, roach_data)
54             for i in range(self.frames)]
55         return RoachActor(frames)
56
57
58 default_roaches = RoachFactory("")
59 t32_roaches = RoachFactory("_32")
60 t21_roaches = RoachFactory("_21")
61 big_roaches = RoachFactory("_big")