Occasional sounds
[tabakrolletjie.git] / tabakrolletjie / enemies.py
1 # Boyd, the friendly, misunderstood turnip loving, light hating space mould
2
3 import random
4
5 import pymunk
6 import pymunk.pygame_util
7 import pygame.draw
8 import pygame.surface
9 import pygame.display
10
11 import pygame.locals as pgl
12
13 from .constants import SCREEN_SIZE, MOULD_CATEGORY, OBSTACLE_CATEGORY
14 from .loader import loader
15 from .sound import sound
16
17 MOULD_FILTER = pymunk.ShapeFilter(
18     mask=MOULD_CATEGORY | OBSTACLE_CATEGORY,
19     categories=MOULD_CATEGORY)
20
21
22 class Mould(pymunk.Body):
23     """A segment of Boyd"""
24
25     def __init__(self, gamestate, space, pos):
26         super(Mould, self).__init__(0, 0, pymunk.Body.STATIC)
27         self.position = pos
28         self._shape = pymunk.Circle(self, 16)
29         space.add(self, self._shape)
30         self._shape.filter = MOULD_FILTER
31         self._resistances = {}
32         self._age = 0
33         self._img = None
34         self._health = 500
35
36     def pygame_pos(self, surface):
37         """Convert to pygame coordinates and offset position so
38            our position is the centre of the image."""
39         # The odd sign combination is because of the pymunk / pygame
40         # transform, but we do it this way to exploit Vec2d math magic
41         return pymunk.pygame_util.to_pygame(self.position + (-16, 16), surface)
42
43     def get_image(self):
44         if not self._img:
45             name = random.choice(
46                 ('mouldA.png', 'mouldB.png', 'mouldC.png'))
47             size = "16" if self._age < 10 else "32" if self._age < 20 else "64"
48             self._img = loader.load_image(size, name)
49         return self._img
50
51     def tick(self, gamestate, space, moulds):
52         """Grow and / or Die"""
53
54         self._age += 1
55
56         # we regain a health every tick, so we heal in the dark
57         if self._health < 100:
58             self._health += 1
59
60         refresh = False
61
62         if (self._age % 15) == 0 and len(moulds) < 1000:
63             # Spawn a new child, if we can
64             spawn = True
65             choice = random.randint(0, 4)
66             if choice == 0:
67                 pos = self.position + (0, 24)
68             elif choice == 1:
69                 pos = self.position + (24, 0)
70             elif choice == 2:
71                 pos = self.position + (-24, 0)
72             else:
73                 pos = self.position + (0, -24)
74             # check for bounds
75             if pos[0] < 0 or pos[0] >= SCREEN_SIZE[0]:
76                 spawn = False
77             if pos[1] < 0 or pos[1] >= SCREEN_SIZE[1]:
78                 spawn = False
79             # Check for free space
80             # We allow some overlap, hence not checking full radius
81             query = space.point_query(pos, 8, MOULD_FILTER)
82             if query:
83                 # for x in query:
84                 #     if not isinstance(x.shape.body, Mould):
85                 #         print x.shape, x.shape.body
86                 spawn = False
87             if spawn:
88                 child = Mould(gamestate, space, pos)
89                 child._health = self._health
90                 moulds.append(child)
91                 refresh = True
92                 if random.randint(0, 10) < 2:
93                     sound.play_sound("mouth_pop_2a.ogg")
94
95         if self._age in (10, 20):
96             # Segment grows in size
97             refresh = True
98             self._img = None # invalidate cached image
99
100         if self._age > 120:
101             # We die of old age
102             space.remove(self, self._shape)
103             moulds.remove(self)
104             refresh = True
105         return refresh
106
107     def damage(self, light_color, intensity, space, moulds):
108         """Take damage for light, adjusted for resistances."""
109         self._health -= 3
110         if self._health <= 0 and self._age <= 120:
111             # We die of damage
112             space.remove(self, self._shape)
113             moulds.remove(self)
114             return True
115         return False
116
117
118 class Boyd(object):
119
120     def __init__(self, gamestate, space):
121         seed = Mould(gamestate, space, (350, 370))
122         self._moulds = [seed]
123         self._image = pygame.surface.Surface(SCREEN_SIZE)
124         self._image.convert_alpha(pygame.display.get_surface())
125         self._draw_moulds()
126
127     def _draw_moulds(self):
128         self._image.fill((0, 0, 0, 0))
129         for m in self._moulds:
130             self._image.blit(m.get_image(),
131                              m.pygame_pos(self._image), None,
132                              0)
133
134     def tick(self, gamestate, space, lights):
135         redraw = False
136         # Handle spawn events
137         for mould in self._moulds[:]:
138             # Handle updates
139             if mould.tick(gamestate, space, self._moulds):
140                 redraw = True
141             # Check for damage
142             lit_by = lights.light_query(mould._shape)
143             for light in lit_by:
144                 # Todo: extract colour and intensity from light
145                 if mould.damage(None, None, space, self._moulds):
146                     redraw = True
147                     break  # we only die once
148         if redraw:
149             self._draw_moulds()
150
151     def render(self, surface):
152         """Draw ourselves"""
153         surface.blit(self._image, (0, 0), None, pgl.BLEND_RGBA_ADD)