source: nagslang/enemies.py@ 334:a3f1b2f0e3fb

Last change on this file since 334:a3f1b2f0e3fb was 334:a3f1b2f0e3fb, checked in by Jeremy Thurgood <firxen@…>, 9 years ago

Physics-related cleanup.

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