source: nagslang/enemies.py@ 385:51deb78cae52

Last change on this file since 385:51deb78cae52 was 385:51deb78cae52, checked in by Stefano Rivera <stefano@…>, 7 years ago

Use a result object to get new drawables back to the area

File size: 9.9 KB
Line 
1import math
2import random
3
4import pymunk
5import pymunk.pygame_util
6from pymunk.vec2d import Vec2d
7
8from nagslang import render
9from nagslang.constants import (COLLISION_TYPE_ENEMY, COLLISION_TYPE_FURNITURE,
10 ACID_SPEED, ACID_DAMAGE, ZORDER_MID)
11from nagslang.events import EnemyDeathEvent, FireEvent
12from nagslang.game_object import (GameObject, SingleShapePhysicser, Result,
13 make_body)
14from nagslang.mutators import FLIP_H
15from nagslang.resources import resources
16from nagslang.utils import vec_with_length
17
18
19def get_editable_enemies():
20 classes = []
21 for cls_name, cls in globals().iteritems():
22 if isinstance(cls, type) and issubclass(cls, Enemy):
23 if hasattr(cls, 'requires'):
24 classes.append((cls_name, cls))
25 return classes
26
27
28def get_alien_image(enemy_type, suffix, *transforms):
29 image_name = 'alien_%s_%s.png' % (enemy_type, suffix)
30 return resources.get_image('creatures', image_name, transforms=transforms)
31
32
33class Enemy(GameObject):
34 """A base class for mobile enemies"""
35 zorder = ZORDER_MID
36 enemy_type = None # Which set of images to use
37 enemy_damage = None
38 health = None
39 impulse_factor = None
40
41 def __init__(self, space, world, position):
42 super(Enemy, self).__init__(
43 self.make_physics(space, position), self.make_renderer())
44 self.world = world
45 self.angle = 0
46
47 def make_physics(self, space, position):
48 raise NotImplementedError
49
50 def make_renderer(self):
51 return render.FacingSelectionRenderer({
52 'left': render.TimedAnimatedRenderer(
53 [get_alien_image(self.enemy_type, '1'),
54 get_alien_image(self.enemy_type, '2')], 3),
55 'right': render.TimedAnimatedRenderer(
56 [get_alien_image(self.enemy_type, '1', FLIP_H),
57 get_alien_image(self.enemy_type, '2', FLIP_H)], 3),
58 })
59
60 def attack(self):
61 raise NotImplementedError
62
63 @classmethod
64 def requires(cls):
65 return [("name", "string"), ("position", "coordinates")]
66
67 def hit(self, weapon):
68 self.lose_health(weapon.damage)
69
70 def lose_health(self, amount):
71 self.health -= amount
72 if self.health <= 0:
73 self.physicser.remove_from_space()
74 EnemyDeathEvent.post(self.physicser.position, self.enemy_type)
75
76 def set_direction(self, dx, dy):
77 vec = vec_with_length((dx, dy), self.impulse_factor)
78 self.angle = vec.angle
79 self.physicser.apply_impulse(vec)
80
81 def collide_with_protagonist(self, protagonist):
82 if self.enemy_damage is not None:
83 protagonist.lose_health(self.enemy_damage)
84
85 def collide_with_claw_attack(self, claw_attack):
86 self.lose_health(claw_attack.damage)
87
88 def ranged_attack(self, range_, speed, damage, type_, reload_time):
89 pos = self.physicser.position
90 target = self.world.protagonist.get_shape().body.position
91
92 r = self.get_space().segment_query(pos, target)
93 for collision in r:
94 shape = collision.shape
95 if (shape in (self.get_shape(), self.world.protagonist.get_shape())
96 or shape.sensor):
97 continue
98 return
99
100 if not self.check_timer('reload_time'):
101 self.start_timer('reload_time', reload_time)
102 vec = Vec2d((target.x - pos.x, target.y - pos.y))
103 if vec.length < range_:
104 vec.length = speed
105 FireEvent.post(pos, vec, damage, type_,
106 COLLISION_TYPE_ENEMY)
107
108 def greedy_move(self, target):
109 """Simple greedy path finder"""
110 def _calc_step(tp, pp):
111 if (tp < pp):
112 step = max(-1, tp - pp)
113 elif (tp > pp):
114 step = min(1, tp - pp)
115 if abs(step) < 0.5:
116 step = 0
117 return step
118 x_step = _calc_step(target[0], self.physicser.position[0])
119 y_step = _calc_step(target[1], self.physicser.position[1])
120 return (x_step, y_step)
121
122 def random_move(self):
123 """Random move"""
124 x_step = random.choice([-1, 0, 1])
125 y_step = random.choice([-1, 0, 1])
126 return x_step, y_step
127
128 def update(self, dt):
129 super(Enemy, self).update(dt)
130 if self.health <= 0:
131 return Result(remove=[self])
132
133
134class DeadEnemy(GameObject):
135 def __init__(self, space, world, position, enemy_type='A'):
136 body = make_body(10, 10000, position, damping=0.5)
137 self.shape = pymunk.Poly(
138 body, [(-20, -20), (20, -20), (20, 20), (-20, 20)])
139 self.shape.friction = 0.5
140 self.shape.collision_type = COLLISION_TYPE_FURNITURE
141 super(DeadEnemy, self).__init__(
142 SingleShapePhysicser(space, self.shape),
143 render.ImageRenderer(resources.get_image(
144 'creatures', 'alien_%s_dead.png' % enemy_type)),
145 )
146
147 @classmethod
148 def requires(cls):
149 return [("name", "string"), ("position", "coordinates")]
150
151
152class PatrollingAlien(Enemy):
153 is_moving = True # Always walking.
154 enemy_type = 'A'
155 health = 42
156 enemy_damage = 15
157 impulse_factor = 50
158
159 def __init__(self, space, world, position, end_position):
160 # An enemy that patrols between the two points
161 super(PatrollingAlien, self).__init__(space, world, position)
162 self._start_pos = position
163 self._end_pos = end_position
164 self._direction = 'away'
165
166 def make_physics(self, space, position):
167 body = make_body(10, pymunk.inf, position, 0.8)
168 shape = pymunk.Circle(body, 30)
169 shape.elasticity = 1.0
170 shape.friction = 0.05
171 shape.collision_type = COLLISION_TYPE_ENEMY
172 return SingleShapePhysicser(space, shape)
173
174 def get_render_angle(self):
175 # No image rotation when rendering, please.
176 return 0
177
178 def get_facing_direction(self):
179 # Enemies can face left or right.
180 if - math.pi / 2 < self.angle <= math.pi / 2:
181 return 'right'
182 else:
183 return 'left'
184
185 def _switch_direction(self):
186 if self._direction == 'away':
187 self._direction = 'towards'
188 else:
189 self._direction = 'away'
190
191 def update(self, dt):
192 # Calculate the step every frame
193 if self._direction == 'away':
194 target = self._end_pos
195 else:
196 target = self._start_pos
197 x_step, y_step = self.greedy_move(target)
198 if abs(x_step) < 1 and abs(y_step) < 1:
199 self._switch_direction()
200 self.set_direction(x_step, y_step)
201 self.ranged_attack(300, ACID_SPEED, ACID_DAMAGE, 'acid', 0.2)
202 return super(PatrollingAlien, self).update(dt)
203
204 @classmethod
205 def requires(cls):
206 return [("name", "string"), ("position", "coordinates"),
207 ("end_position", "coordinates")]
208
209
210class ChargingAlien(Enemy):
211 # Simplistic charging of the protagonist
212 is_moving = False
213 enemy_type = 'B'
214 health = 42
215 enemy_damage = 20
216 impulse_factor = 300
217
218 def __init__(self, space, world, position, attack_range=100):
219 super(ChargingAlien, self).__init__(space, world, position)
220 self._range = attack_range
221
222 def make_physics(self, space, position):
223 body = make_body(100, pymunk.inf, position, 0.8)
224 shape = pymunk.Circle(body, 30)
225 shape.elasticity = 1.0
226 shape.friction = 0.05
227 shape.collision_type = COLLISION_TYPE_ENEMY
228 return SingleShapePhysicser(space, shape)
229
230 def get_render_angle(self):
231 # No image rotation when rendering, please.
232 return 0
233
234 def get_facing_direction(self):
235 # Enemies can face left or right.
236 if - math.pi / 2 < self.angle <= math.pi / 2:
237 return 'right'
238 else:
239 return 'left'
240
241 def _calc_movement(self):
242 pos = self.physicser.position
243 target = self.world.protagonist.get_shape().body.position
244 if pos.get_distance(target) > self._range:
245 # stop
246 self.is_moving = False
247 return 0, 0
248 self.is_moving = True
249 dx, dy = self.greedy_move(target)
250 return dx, dy
251
252 def update(self, dt):
253 # Calculate the step every frame
254 # Distance to the protagonist
255 self.ranged_attack(300, ACID_SPEED, ACID_DAMAGE, 'acid', 0.2)
256 dx, dy = self._calc_movement()
257 self.set_direction(dx, dy)
258 return super(ChargingAlien, self).update(dt)
259
260 @classmethod
261 def requires(cls):
262 return [("name", "string"), ("position", "coordinates"),
263 ("attack_range", "distance")]
264
265
266class RunAndGunAlien(ChargingAlien):
267 # Simplistic shooter
268 # Move until we're in range, and then randomly
269 impulse_factor = 90
270 is_moving = True
271
272 def __init__(self, space, world, position, attack_range=100):
273 super(RunAndGunAlien, self).__init__(space, world, position,
274 attack_range)
275 self.count = 0
276 self._old_move = (0, 0)
277
278 def make_physics(self, space, position):
279 body = make_body(10, pymunk.inf, position, 0.8)
280 shape = pymunk.Circle(body, 30)
281 shape.elasticity = 1.0
282 shape.friction = 0.05
283 shape.collision_type = COLLISION_TYPE_ENEMY
284 return SingleShapePhysicser(space, shape)
285
286 def _calc_movement(self):
287 pos = self.physicser.position
288 target = self.world.protagonist.get_shape().body.position
289 if pos.get_distance(target) < self._range:
290 if self.count > 10:
291 self._old_move = self.random_move()
292 self.count = 0
293 return self._old_move
294 else:
295 return self.greedy_move(target)
296
297 def update(self, dt):
298 self.count += 1
299 return super(RunAndGunAlien, self).update(dt)
300
301 @classmethod
302 def requires(cls):
303 return [("name", "string"), ("position", "coordinates"),
304 ("attack_range", "distance")]
Note: See TracBrowser for help on using the repository browser.