e4c868e89ae3dabd6d4ca6d3b9b08448ad93ce76
[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 from .constants import (SCREEN_SIZE, MOULD_CATEGORY, OBSTACLE_CATEGORY,
12                         TURNIP_CATEGORY)
13 from .loader import loader
14 from .sound import sound
15
16 MOULD_FILTER = pymunk.ShapeFilter(
17     mask=MOULD_CATEGORY | OBSTACLE_CATEGORY,
18     categories=MOULD_CATEGORY)
19
20 EAT_TURNIP_FILTER = pymunk.ShapeFilter(mask=TURNIP_CATEGORY)
21
22
23 # Boyd parameters
24 SPAWN_RATE = 10
25 MAX_AGE = 60
26 MAX_ELEMENTS = 400
27 MAX_HEALTH = 100
28
29 # Increase in health per day
30 DAY_HEALTH = 10
31
32 HEAL_FACTOR = 1
33
34 MOULD_STAGES = [15, 25]
35
36
37 class Mould(pymunk.Body):
38     """A segment of Boyd"""
39
40     def __init__(self, gamestate, space, pos, resistances):
41         super(Mould, self).__init__(0, 0, pymunk.Body.STATIC)
42         self.position = pos
43         self._shape = pymunk.Circle(self, 16)
44         space.add(self, self._shape)
45         self._shape.filter = MOULD_FILTER
46         self._age = 0
47         self._img = None
48         self._health = 500
49         self.has_eyeball = False
50         self._eyeball = None
51         self._resistances = resistances
52
53     def pygame_pos(self, surface):
54         """Convert to pygame coordinates and offset position so
55            our position is the centre of the image."""
56         # The odd sign combination is because of the pymunk / pygame
57         # transform, but we do it this way to exploit Vec2d math magic
58         return pymunk.pygame_util.to_pygame(self.position + (-16, 16), surface)
59
60     def get_image(self):
61         if not self._img:
62             name = random.choice(
63                 ('mouldA.png', 'mouldB.png', 'mouldC.png'))
64             size = "16" if self._age < MOULD_STAGES[0] else "32" if self._age < MOULD_STAGES[1] else "64"
65             self._img = loader.load_image(size, name)
66         return self._img
67
68     def get_eyeball(self):
69         if not self._eyeball:
70             name = random.choice(
71                 ('eyeballA.png', 'eyeballB.png', 'eyeballC.png'))
72             self._eyeball = loader.load_image("32", name)
73         return self._eyeball
74
75     def set_health(self, new_health):
76         self._health = new_health
77
78     def tick(self, gamestate, space, moulds):
79         """Grow and / or Die"""
80
81         self._age += 1
82
83         # we regain a health every tick, so we heal in the dark
84         if self._health < MAX_HEALTH:
85             self._health += HEAL_FACTOR
86
87         refresh = False
88
89         if (self._age % SPAWN_RATE) == 0 and len(moulds) < MAX_ELEMENTS:
90             # Spawn a new child, if we can
91             spawn = True
92             choice = random.randint(0, 3)
93             if choice == 0:
94                 pos = self.position + (0, 24)
95             elif choice == 1:
96                 pos = self.position + (24, 0)
97             elif choice == 2:
98                 pos = self.position + (-24, 0)
99             else:
100                 pos = self.position + (0, -24)
101             # check for bounds
102             if pos[0] < 0 or pos[0] >= SCREEN_SIZE[0]:
103                 spawn = False
104             if pos[1] < 0 or pos[1] >= SCREEN_SIZE[1]:
105                 spawn = False
106             # Check for free space
107             # We allow some overlap, hence not checking full radius
108             query = space.point_query(pos, 8, MOULD_FILTER)
109             if query:
110                 spawn = False
111             if spawn:
112                 child = Mould(gamestate, space, pos, self._resistances)
113                 child._health = self._health
114                 moulds.append(child)
115                 refresh = True
116                 if random.randint(0, 10) < 2:
117                     sound.play_sound("mouth_pop_2a.ogg")
118
119         if self._age in MOULD_STAGES:
120             # We grow in size
121             refresh = True
122             self._img = None  # invalidate cached image
123
124         if self._age > MOULD_STAGES[1] and random.randint(0, 500) < 1:
125             # Maybe we grow an eyeball
126             self.has_eyeball = True
127
128         if self._age > MAX_AGE:
129             # We die of old age
130             space.remove(self, self._shape)
131             moulds.remove(self)
132             refresh = True
133         else:
134             # Check for turnips we can eat
135             # Note that we can only eat a tick after we spawn
136             query = space.point_query(self.position, 16, EAT_TURNIP_FILTER)
137             if query:
138                 query[0].shape.body.turnip.eaten = True
139         return refresh
140
141     def damage(self, light, space, moulds):
142         """Take damage for light, adjusted for resistances."""
143         damage = light.base_damage()
144         colour = light.colour
145         damage = int(damage * (3 - self._resistances.get(colour, 0)) / 3.0)
146         self._health -= damage
147         if self._health <= 0 and self._age <= MAX_AGE:
148             # We die of damage
149             space.remove(self, self._shape)
150             moulds.remove(self)
151             return True
152         return False
153
154
155 class Boyd(object):
156
157     def __init__(self, gamestate, space):
158         self._moulds = []
159         self._seen_colours = set()
160         for position in gamestate.get_spawn_positions():
161             seed = Mould(gamestate, space, position,
162                          gamestate.resistances)
163             seed.set_health(MAX_HEALTH + gamestate.days * DAY_HEALTH)
164             self._moulds.append(seed)
165         self._image = pygame.surface.Surface(SCREEN_SIZE)
166         self._image = self._image.convert_alpha(pygame.display.get_surface())
167         self._draw_moulds()
168
169     def _draw_moulds(self):
170         self._image.fill((0, 0, 0, 0))
171         for m in self._moulds:
172             self._image.blit(m.get_image(),
173                              m.pygame_pos(self._image), None,
174                              0)
175         for m in self._moulds:
176             if m.has_eyeball:
177                 self._image.blit(m.get_eyeball(), m.pygame_pos(self._image),
178                                  None, 0)
179
180     def tick(self, gamestate, space, lights):
181         redraw = False
182         # Handle spawn events
183         for mould in self._moulds[:]:
184             # Handle updates
185             if mould.tick(gamestate, space, self._moulds):
186                 redraw = True
187             # Check for damage
188             lit_by = lights.light_query(mould._shape)
189             for light in lit_by:
190                 self._seen_colours.add(light.colour)
191                 if mould.damage(light, space, self._moulds):
192                     redraw = True
193                     break  # we only die once
194         if redraw:
195             self._draw_moulds()
196
197     def render(self, surface):
198         """Draw ourselves"""
199         surface.blit(self._image, (0, 0), None, 0)
200
201     def alive(self):
202         return len(self._moulds) > 0
203
204     def update_resistances(self, gamestate):
205         for colour in self._seen_colours:
206             cur_reistance = gamestate.resistances.get(colour, 0)
207             gamestate.resistances[colour] = cur_reistance + 2
208         for colour in gamestate.resistances:
209             gamestate.resistances[colour] -= 1
210             if gamestate.resistances[colour] > 3:
211                 gamestate.resistances[colour] = 3
212             if gamestate.resistances[colour] < 0:
213                 gamestate.resistances[colour] = 0