Merge branch 'master' of ctpug.org.za:koperkapel
[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 WorldRoach(object):
37     """A roach proxy with no properties for display on the game level."""
38
39     def __init__(self):
40         self.smart = False
41         self.strong = False
42         self.fast = False
43
44
45 class RoachFactory:
46
47     def __init__(self, suffix, frames=4):
48         self.suffix = suffix
49         self.frames = 4
50
51     def assemble_frame(self, i, color, roach_data):
52         roach = images.load("roach%s/roach_%d" % (self.suffix, i + 1))
53         eyes = images.load("roach%s/eyes_%d" % (self.suffix, i + 1))
54         frame = roach.copy()
55         frame.fill(color, None, BLEND_RGBA_MULT)
56         frame.blit(eyes, (0, 0))
57         return frame
58
59     def assemble(self, roach_data):
60         color = roach_serum_color(roach_data)
61         frames = [
62             self.assemble_frame(i, color, roach_data)
63             for i in range(self.frames)]
64         return RoachActor(frames)
65
66
67 default_roaches = RoachFactory("")
68 t32_roaches = RoachFactory("_32")
69 t21_roaches = RoachFactory("_21")
70 big_roaches = RoachFactory("_big")
71 roaches_quartet = RoachFactory("_quartet")
72 roaches_nonet = RoachFactory("_nonet")