source: nagslang/enemies.py@ 310:fa408430a174

Last change on this file since 310:fa408430a174 was 310:fa408430a174, checked in by Stefano Rivera <stefano@…>, 8 years ago

Now *both* types of enemies die

File size: 8.2 KB
Line 
1import math
2
3import pymunk
4import pymunk.pygame_util
5
6from nagslang import render
7from nagslang.constants import (COLLISION_TYPE_ENEMY, COLLISION_TYPE_BOX,
8 ZORDER_MID)
9from nagslang.events import EnemyDeathEvent
10from nagslang.game_object import GameObject, SingleShapePhysicser, make_body
11from nagslang.mutators import FLIP_H
12from nagslang.resources import resources
13
14
15def get_editable_enemies():
16 classes = []
17 for cls_name, cls in globals().iteritems():
18 if isinstance(cls, type) and issubclass(cls, Enemy):
19 if hasattr(cls, 'requires'):
20 classes.append((cls_name, cls))
21 return classes
22
23
24class Enemy(GameObject):
25 """A base class for mobile enemies"""
26 enemy_type = None # Image to use for dead Enemy
27
28 def __init__(self, space, world, position):
29 self._setup_physics(space, position)
30 self._setup_renderer()
31 self.health = 42
32
33 super(Enemy, self).__init__(
34 self._physicser, self.renderer)
35 self.zorder = ZORDER_MID
36 self.world = world
37
38 def _get_image(self, name, *transforms):
39 return resources.get_image('creatures', name, transforms=transforms)
40
41 def _setup_physics(self, space, position):
42 raise NotImplementedError
43
44 def _setup_renderer(self):
45 raise NotImplementedError
46
47 def attack(self):
48 raise NotImplementedError
49
50 @classmethod
51 def requires(cls):
52 return [("name", "string"), ("position", "coordinates")]
53
54 def hit(self, weapon):
55 self.lose_health(weapon.damage)
56
57 def lose_health(self, amount):
58 self.health -= amount
59 if self.health < 0:
60 self.physicser.remove_from_space()
61 self.remove = True
62 EnemyDeathEvent.post(self.physicser.position, self.enemy_type)
63
64
65class DeadEnemy(GameObject):
66 def __init__(self, space, world, position, enemy_type='A'):
67 body = make_body(10, 10000, position, damping=0.5)
68 self.shape = pymunk.Poly(
69 body, [(-20, -20), (20, -20), (20, 20), (-20, 20)])
70 self.shape.friction = 0.5
71 self.shape.collision_type = COLLISION_TYPE_BOX
72 super(DeadEnemy, self).__init__(
73 SingleShapePhysicser(space, self.shape),
74 render.ImageRenderer(resources.get_image(
75 'creatures', 'alien_%s_dead.png' % enemy_type)),
76 )
77
78 @classmethod
79 def requires(cls):
80 return [("name", "string"), ("position", "coordinates")]
81
82
83class PatrollingAlien(Enemy):
84 is_moving = True # Always walking.
85 enemy_type = 'A'
86
87 def __init__(self, space, world, position, end_position):
88 # An enemy that patrols between the two points
89 super(PatrollingAlien, self).__init__(space, world, position)
90 self._start_pos = position
91 self._end_pos = end_position
92 self._direction = 'away'
93
94 def _setup_physics(self, space, position):
95 self._body = make_body(10, pymunk.inf, position, 0.8)
96
97 self._shape = pymunk.Circle(self._body, 30)
98
99 self._shape.elasticity = 1.0
100 self._shape.friction = 0.05
101 self._shape.collision_type = COLLISION_TYPE_ENEMY
102 self._physicser = SingleShapePhysicser(space, self._shape)
103 self.impulse_factor = 50
104 self.angle = 0
105
106 def _setup_renderer(self):
107 self.renderer = render.FacingSelectionRenderer({
108 'left': render.TimedAnimatedRenderer(
109 [self._get_image('alien_A_1.png'),
110 self._get_image('alien_A_2.png')], 3),
111 'right': render.TimedAnimatedRenderer(
112 [self._get_image('alien_A_1.png', FLIP_H),
113 self._get_image('alien_A_2.png', FLIP_H)], 3),
114 })
115
116 def get_render_angle(self):
117 # No image rotation when rendering, please.
118 return 0
119
120 def get_facing_direction(self):
121 # Enemies can face left or right.
122 if - math.pi / 2 < self.angle <= math.pi / 2:
123 return 'right'
124 else:
125 return 'left'
126
127 def _switch_direction(self):
128 if self._direction == 'away':
129 self._direction = 'towards'
130 else:
131 self._direction = 'away'
132
133 def set_direction(self, dx, dy):
134 self.angle = pymunk.Vec2d((dx, dy)).angle
135 self._body.apply_impulse(
136 (dx * self.impulse_factor, dy * self.impulse_factor))
137
138 def update(self, seconds):
139 # Calculate the step every frame
140 if self._direction == 'away':
141 target = self._end_pos
142 else:
143 target = self._start_pos
144 x_step = 0
145 y_step = 0
146 if (target[0] < self._body.position[0]):
147 x_step = max(-1, target[0] - self._body.position[0])
148 elif (target[0] > self._body.position[0]):
149 x_step = min(1, target[0] - self._body.position[0])
150 if abs(x_step) < 0.5:
151 x_step = 0
152 if (target[1] < self._body.position[1]):
153 y_step = max(-1, target[1] - self._body.position[1])
154 elif (target[1] > self._body.position[1]):
155 y_step = min(1, target[1] - self._body.position[1])
156 if abs(y_step) < 0.5:
157 y_step = 0
158 if abs(x_step) < 1 and abs(y_step) < 1:
159 self._switch_direction()
160 self.set_direction(x_step, y_step)
161 super(PatrollingAlien, self).update(seconds)
162
163 def collide_with_protagonist(self, protagonist):
164 protagonist.lose_health(15)
165
166 @classmethod
167 def requires(cls):
168 return [("name", "string"), ("position", "coordinates"),
169 ("end_position", "coordinates")]
170
171
172class ChargingAlien(Enemy):
173 # Simplistic charging of the protagonist
174 is_moving = False
175 enemy_type = 'B'
176
177 def __init__(self, space, world, position, attack_range=100):
178 super(ChargingAlien, self).__init__(space, world, position)
179 self._range = attack_range
180
181 def _setup_physics(self, space, position):
182 self._body = make_body(100, pymunk.inf, position, 0.8)
183
184 self._shape = pymunk.Circle(self._body, 30)
185
186 self._shape.elasticity = 1.0
187 self._shape.friction = 0.05
188 self._shape.collision_type = COLLISION_TYPE_ENEMY
189 self._physicser = SingleShapePhysicser(space, self._shape)
190 self.impulse_factor = 300
191 self.angle = 0
192
193 def _setup_renderer(self):
194 self.renderer = render.FacingSelectionRenderer({
195 'left': render.TimedAnimatedRenderer(
196 [self._get_image('alien_B_1.png'),
197 self._get_image('alien_B_2.png')], 3),
198 'right': render.TimedAnimatedRenderer(
199 [self._get_image('alien_B_1.png', FLIP_H),
200 self._get_image('alien_B_2.png', FLIP_H)], 3),
201 })
202
203 def get_render_angle(self):
204 # No image rotation when rendering, please.
205 return 0
206
207 def get_facing_direction(self):
208 # Enemies can face left or right.
209 if - math.pi / 2 < self.angle <= math.pi / 2:
210 return 'right'
211 else:
212 return 'left'
213
214 def set_direction(self, dx, dy):
215 self.angle = pymunk.Vec2d((dx, dy)).angle
216 self._body.apply_impulse(
217 (dx * self.impulse_factor, dy * self.impulse_factor))
218
219 def update(self, seconds):
220 # Calculate the step every frame
221 # Distance to the protagonist
222 pos = self._body.position
223 target = self.world.protagonist.get_shape().body.position
224 if pos.get_distance(target) > self._range:
225 # stop
226 self.is_moving = False
227 return
228 self.is_moving = True
229 x_step = 0
230 y_step = 0
231 if (target[0] < pos[0]):
232 x_step = max(-1, target[0] - pos[0])
233 elif (target[0] > pos[0]):
234 x_step = min(1, target[0] - pos[0])
235 if abs(x_step) < 0.5:
236 x_step = 0
237 if (target[1] < pos[1]):
238 y_step = max(-1, target[1] - pos[1])
239 elif (target[1] > pos[1]):
240 y_step = min(1, target[1] - pos[1])
241 if abs(y_step) < 0.5:
242 y_step = 0
243 self.set_direction(x_step, y_step)
244 super(ChargingAlien, self).update(seconds)
245
246 def collide_with_protagonist(self, protagonist):
247 protagonist.lose_health(20)
248
249 @classmethod
250 def requires(cls):
251 return [("name", "string"), ("position", "coordinates"),
252 ("attack_range", "distance")]
Note: See TracBrowser for help on using the repository browser.